14

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

ThePizzle
  • 1,086
  • 4
  • 12
  • 20

4 Answers4

22

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
5

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;
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • You can "see" them similar in the some cases, but it doesn't mean it works under the hood that way. console.log('a'=='b' && 'c') is different from console.log('a'=='b'?'c':'b') – Anh Nguyen Jul 08 '22 at 11:30
4

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.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
0

The other answers are more than adequate, I'm including my answer here for posterity just in case someone else's brain works like mine:

The result of the boolean || and boolean && operators will always be the result of the last expression evaluated, taking into consideration short circuiting.

So, for ||, if the first expression is truthy, short circuit evaluation means that the rest is ignored, and the result will be the value of that first expression. If it's falsy, evaluation must continue to the second expression, and the result will be the result of that second expression no matter whether it's truthy or falsy.

Likewise for &&, if the first expression is falsy then evaluation stops and the result is the result of that first expression, if it's truthy then evaluation continues and the result is the result of the second expression.

Jason
  • 13,606
  • 2
  • 29
  • 40