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
The 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 to true
by definition (since it's the opposite), so it returns the second operand (undefined
)
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).
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