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
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
Share
Improve this question
asked Jan 26, 2014 at 19:09
Michael RadionovMichael Radionov
13.3k2 gold badges58 silver badges75 bronze badges
1
- 1 possible duplicate of What does the || operator do? – Stephen Commented Jan 26, 2014 at 19:14
3 Answers
Reset to default 15The logical OR
operator isn't commutative like +
, *
, etc. It returns the first expression which can be converted into true
. (Source Mozilla Doc)
In
false || undefined
,false
can't be converted totrue
by definition (since it's the opposite), so it returns the second operand (undefined
)In
undefined || false
,undefined
is a value, but considered asfalse
in Javascript, so the logical operator evaluate the second operand and returnsfalse
(because both operands are false).
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.