Question

What is the explanation for behavior of the "||" operator (logical OR), when using it with false and undefined on both sides in JavaScript?

1)

> false || undefined
undefined

2)

> undefined || false
false
Was it helpful?

Solution

The logical OR operator isn't commutative like +, *, etc. It returns the first expression which can be converted into true. (Source Mozilla Doc)

  1. In false || undefined, false can't be converted to true by definition (since it's the opposite), so it returns the second operand (undefined)

  2. In undefined || false, undefined is a value, but considered as false in Javascript, so the logical operator evaluate the second operand and returns false (because both operands are false).

OTHER TIPS

According to Logical Operators in Mozilla Docs:

Logical OR (||)

expr1 || expr2

Returns 'expr1' if it can be converted to true; otherwise, returns 'expr2.

1) in case false || undefined: false(expr1) can not be converted to true, so undefined(expr2) is returned

2) in case undefined || false: undefined(expr1) can not be converted to true, so false(expr2) is returned

This question is not related particularly to just false and undefined but, to any of the Falsy Values in Javascript. Note that there are a total of six falsy values in Javascript:

  • false.
  • 0 (zero)
  • '' or "" (an empty string)
  • null
  • undefined
  • NaN

When you run the logical OR operation between two Falsy Values, say <left value> || <right value> in JS, it always returns the value on the right side of the OR operator. Reason being that the OR operator, as per its implementation in ECMAScript Engines, in general returns the left value if it can be coerced to true. But, if the value on the left side of the operator cannot be coerced to true, the right value is always returned no matter what the value on the right is, instead of getting coerced as one might expect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top