Why does false || null
return a different result than null || false
?
Can I safely rely on return myVar || false
returning false if myVar is either null
or false
, but true
otherwise?
All Combinations:
false || null
null
null || false
false
true || null
true
null || true
true
null is one of JavaScript's primitive values. It is neither equal to boolean true nor equal to boolean false because it's value is undefined.
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.
Lifted operators For the equality operator == , if both operands are null , the result is true , if only one of the operands is null , the result is false ; otherwise, the contained values of operands are compared. For the inequality operator !=
Comparing any variable with NULL will always evaluate to FALSE, regardless if it's value, unless IS NULL or IS NOT NULL is used.
The ||
operator in JavaScript doesn't necessarily return true
or false
. It's exact behavior is this:
If the first operand is truthy, it evaluates to the first operand. Otherwise, it evaluates to the second.
This works as expected given two boolean values, but as you have noticed, you can also use it with any other value. In both of your examples, the first operand is falsey. Thus, both expressions evaluate to the second operand.
Note about one way this is used: The behavior of ||
is often used to create default arguments:
function foo(optionalArg) {
optionalArg = optionalArg || "default!";
console.log(optionalArg);
}
foo("test");
foo();
If optionalArg
is omitted, its values implicitly becomes undefined
. Because undefined
is falsey, undefined || "default!"
evaluates to "default!"
. Note that this style of default args can backfire if you pass a falsey value, like 0
or ""
. It's more robust to explicitly check for undefined
. In ECMAScript 6, you can do this with a default value within the parameter list to be more readable:
function foo(optionalArg = "default!") {
console.log(optionalArg);
}
foo("test");
foo(false);
foo(undefined);
foo();
When you have || between two variables the following happens.
Example: a || b
Another way to write this is:
if (a) {
return a;
}
return b;
Or:
a ? a : b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With