Why a = 0 || false
returns false
but not 0
in JavaScript?
Output from the debug console:
> a = 0 || false
false
> a
false
> a = 0
0
> a = a || false
false
> a
false
Why a = 0 || false
returns false
but not 0
in JavaScript?
Output from the debug console:
> a = 0 || false
false
> a
false
> a = 0
0
> a = a || false
false
> a
false
a = 0 || false
Let's decompose it, or let's follow javascript's logic.
a
||
tells us to pick first if it is truthy, otherwise pick second.0
is NOT truthy, then pick the second option, which is obviously false
a=0
is an assigment.
However, when you do a=0 || false
, your expression converts to 0 || false
, the result of which is false
.
a = a
is no logical comparison but just an assign, so all you do is 0 = 0 || false
and since 0 is considered false
Why not 0
then ?
because a condition always returns a boolean so 0 -> false
if you wanted to check if a equals a
you'd have to write a == a
a = 0;
console.log(a, a = a || false, a == a || false );
This is because the last evaluated value for the operator ||
is the operand false
. This is in keeping with short circuit evaluation for logical operator. If your expression were:
a = 0 || 22
The output would be 22
and not a boolean (true
OR false
). Explanation: same as above. The last evaluated expression is operand 22
and that is returned.
Let me know if that answered your question.
Ref: https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c