Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against "" using the === operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !== operator:
if (strValue !== "") {
// strValue was not an empty string
}
Answer from Brian Dukes on Stack OverflowVideos
Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against "" using the === operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !== operator:
if (strValue !== "") {
// strValue was not an empty string
}
For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(Note that strings aren't the only variables with a length attribute, arrays have them as well, for example.)
Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
const isEmpty = (str) => (!str?.length);
It will check the length, returning undefined in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.
For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
If you want, you can monkey-patch the String prototype like this:
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
You wrote:
document.getElementById("demo").innerHTML = String(null); //returns an empty string document.getElementById("demo").innerHTML = null.toString(); //returns "null" string
But both assertions are false, I am afraid.
String(null) never returns an empty string, rather a primitive of type string whose value is "null".
BTW, the form String(null) should never be used.
new String(null), on the other hand, returns an object, an instance of String (note the uppercase first letter) whose primitive value ([[PrimitiveValue]] internal property) is "null".
null.toString() raises an error in every JS engine I know. Even though null might be considered an object (due to a historical bug), it has no property, therefore no 'method' toString() (I quote the 'method' because there are no methods in JS, really).
Anyway, to be consistent, you could use this :
document.getElementById("demo").innerHTML = whateverVariable || '';
Should whateverVariable be falsy (null, undefined, 0, -0, '', NaN or false), empty string '' will be assigned to document.getElementById("demo").innerHTML.
I don't think there's a real convention here; Element.innerHTML is a property that tests the given value to determine what to do. In Safari it behaves like this:
if (value === null || value === '') {
// remove all contents
} else {
// parse string representation of value into the elements contents
}
So both "" (empty string) and null are considered the same and the assignment will just remove all contents; I couldn't find conclusive evidence that would suggest other browsers work this way, but it seems very likely that it should be considered an implementation detail that you shouldn't rely upon (see update).
That said, the documented way of clearing an element is by assigning the empty string to this property.
Update
I've found this (inconclusive) email thread about the subject, highlighting that this behaviour is not standardised:
For .innerHTML = null Opera and Internet Explorer act as if the literal string "null" was used. Firefox acts as if "" was used.
In programming, truthiness or falsiness is that quality of those boolean expressions which don't resolve to an actual boolean value, but which nevertheless get interpreted as a boolean result.
In the case of C, any expression that evaluates to zero is interpreted to be false. In Javascript, the expression value in
if(value) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
See Also
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
The set of "truthy" and "falsey" values in JavaScript comes from the ToBoolean abstract operation defined in the ECMAScript spec, which is used when coercing a value to a boolean:
+--------------------------------------------------------------------------+
| Argument Type | Result |
|---------------+----------------------------------------------------------|
| Undefined | false |
|---------------+----------------------------------------------------------|
| Null | false |
|---------------+----------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------+----------------------------------------------------------|
| Number | The result is false if the argument is +0, โ0, or NaN; |
| | otherwise the result is true. |
|---------------+----------------------------------------------------------|
| String | The result is false if the argument is the empty String |
| | (its length is zero); otherwise the result is true. |
|---------------+----------------------------------------------------------|
| Object | true |
+--------------------------------------------------------------------------+
From this table, we can see that null and undefined are both coerced to false in a boolean context. However, your fields.length === 0 does not map generally onto a false value. If fields.length is a string, then it will be treated as false (because a zero-length string is false), but if it is an object (including an array) it will coerce to true.
If fields should be a string, then !fields is a sufficient predicate. If fields is an array, your best check might be:
if (!fields || fields.length === 0)
Starting with:
return (!value || value == undefined || value == "" || value.length == 0);
Looking at the last condition, if value == "", it's length MUST be 0. Therefore drop it:
return (!value || value == undefined || value == "");
But wait! In JS, an empty string is false. Therefore, drop value == "":
return (!value || value == undefined);
And !undefined is true, so that check isn't needed. So we have:
return (!value);
And we don't need parentheses:
return !value
Q.E.D.
There are just a few revisions I would make.
First, always use === instead of == in Javascript. You can read more about that on Stack Overflow.
Second, since undefined is mutable, I would reccomend using
typeof value === "undefined"
instead of
value === undefined
Third, I would remove the !value and value === "" conditions. They are redundant.
My Revision
I would use a slightly different approach than you:
String.isNullOrEmpty = function(value) {
return !(typeof value === "string" && value.length > 0);
}
This checks if the type of the value is "string" (and thus non-null and not undefined), and if it is not empty. If so, it is not null or empty.
Note that this returns true for non-string inputs, which might not be what you want if you wanted to throw an error for an unexpected input type.
When declaring variables what's the best practice?
My manager asked me to change a declaration from null to an empty string and I don't really see why?
Edit: This is for JavaScript
They closed my question on SO because it's not reproducible, but that's exactly why I posted, because code isn't behaving as it should.
Anyway, I 'm receiving a JSON result from a web service. It looks something like this:
{ "data": [{ "id": "123ABC", "name" : "Test 1" }, { "id": "", "name" : "Test 2" }] }I 'm looping through the data array and need to determine if an id exists or not:
for( const item of data ) {
if( item.id !== null && item.id.trim().length > 0 ) {
doSomething();
} else {
doSomethingElse();
}
}My problem is that doSomething() fires for the first item ("123ABC") but also fires for the second where the id is empty.
I've tried spitting out the values for the second item:
console.log("NULL ", item.id === null);
console.log("EMPTY ", item.id.trim().length === 0);and results are
NULL false EMPTY false
so I'm wondering if there's something strange about the id value.
Your function should be like this:
function (key, value) {
return (value === null) ? "" : value;
}
If the value is null, then it returns an empty string.
If you can replace null-s with empty strings on serialized string, do something like this:
data = JSON.parse(JSON.stringify(data).replace(/\:null/gi, "\:\"\""));
You can use ||:
x = x || undefined;
If "x" has any falsy value (including the empty string), it will end up as undefined.
editโNow it's 2024, and the above is fine, but there's a better way to make the above sort of "fix" to values when you do care about things like 0 and the empty string:
x ??= undefined;
The ?? operator, and the assignment operator ??=, work like || but it only tests for null and undefined. Thus you don't have the annoying problem with other "falsy" values. The statement above will make sure that the value of x is undefined if it's currently either null or undefined.
So good old || still works when you want to "normalize" any falsy value, and ?? is great for when you're just worried about null and undefined.
You could also use a function :
// "def" means "default (to undefined)"
function def(v) { if (v) return v; }
x = def(x);
y = def(y);
Well, you need at least two lines (cheating a bit) =D
You can use Nullish coalescing operator (??) that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
Working Demo :
let number = null;
document.getElementById('numberText').innerHTML = number ?? ''
<p id="numberText"></p>
This will check if the variable's type is number and if not it won't render anything:
typeof number === 'number' ? number : ''