Using the node.js console (node 0.10.24)
> var x = (undefined && true);
undefined
> x;
undefined
> x = (true && undefined);
undefined
> x;
undefined
Why does the comparison return undefined? I would expect it to return false since undefined is considered "falsey".
The &&
operator proceeds by internally coercing the values of the expressions to boolean, but the result of the operator is always the actual, uncoerced value of the first expression that failed (i.e., that was falsey).
Thus (true && undefined)
will result in undefined
because true
is not falsey. Similarly, (true && 0)
would evaluate to 0
.
In javascript ||
and &&
are not guaranteed to return boolean values, and will only do so when the operands are booleans.
a = b || c
is essentially a shortcut for:
a = b ? b : c;
a = b && c
is essentially a shortcut for:
a = b ? c : b;
//or
a = !b ? b : c;
To formalize what others are saying, here's what the ECMAScript specification says about how the logical AND operator is evaluated:
- Let lref be the result of evaluating LogicalANDExpression.
- Let lval be GetValue(lref).
- If ToBoolean(lval) is false, return lval.
- Let rref be the result of evaluating BitwiseORExpression.
- Return GetValue(rref).
And perhaps most relevant, the note at the bottom of section 11.11:
The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
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