Krishan Gupta Krishan Gupta - 9 days ago 5
Javascript Question

Javascript: why does (false || null) return null, while (null || false) returns false?

Any explanation for the output for

false || null
in javascript and why it's different than
null || false
?

Can I safely rely on it in code, for example
return myVar || false
to return false if myVar is either
null
or
false
, but
true
otherwise? Thanks!

All Combinations:

false || null


null

null || false


false

true || null


true

null || true


true

qxz qxz
Answer

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();