Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (false || null) return null, while (null || false) returns false?

Tags:

javascript

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

like image 323
Krishan Gupta Avatar asked Nov 26 '16 02:11

Krishan Gupta


People also ask

Why is null == false false?

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.

Does null return true or false?

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.

IS null == true?

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 !=

Does null return false?

Comparing any variable with NULL will always evaluate to FALSE, regardless if it's value, unless IS NULL or IS NOT NULL is used.


2 Answers

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();
like image 72
qxz Avatar answered Oct 06 '22 19:10

qxz


When you have || between two variables the following happens.

Example: a || b

  1. It checks if the a is truthy. If it is then it returns it. If it is not then it checks the next value.
  2. If it hasn't returned a value yet then it returns the next value no matter what.

Another way to write this is:

if (a) {
    return a;
}
return b;

Or:

a ? a : b;
like image 21
kjonsson Avatar answered Oct 06 '22 20:10

kjonsson