Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, why does (undefined && true) return undefined? [duplicate]

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".

like image 422
ThePizzle Avatar asked Mar 31 '14 16:03

ThePizzle


3 Answers

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.

like image 118
Pointy Avatar answered Nov 16 '22 19:11

Pointy


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;
like image 45
zzzzBov Avatar answered Nov 16 '22 19:11

zzzzBov


To formalize what others are saying, here's what the ECMAScript specification says about how the logical AND operator is evaluated:

  1. Let lref be the result of evaluating LogicalANDExpression.
  2. Let lval be GetValue(lref).
  3. If ToBoolean(lval) is false, return lval.
  4. Let rref be the result of evaluating BitwiseORExpression.
  5. 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.

like image 4
Andrew Whitaker Avatar answered Nov 16 '22 20:11

Andrew Whitaker