1

My questions might be silly, but why in the expression

var query;
var n =  query && query.length > 0;

n is 'undefined' and not false? I expected the expression to be evaluates as a boolean. It made me curious.

Anelook
  • 1,277
  • 3
  • 17
  • 28
  • Logical operators (AND and OR) return the value that determines the outcome of the evaluation. That's just how it is. See the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators): *"Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the `&&` and `||` operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value."* – Felix Kling Jun 26 '14 at 06:00
  • I suppose anything done with undefined is undefined. i.e. you are doing '&&' with undefined. – shahkalpesh Jun 26 '14 at 06:00

1 Answers1

0

&& evaluates its left operand. If that left operand is falsy, it evaluates to its left operand. Otherwise, it evaluates to its right operand.

Since JavaScript doesn’t generally have strong typing, this works in the same way as a boolean result for the most part, and allows for convenient tricks, like this one, with ||:

var requestAnimationFrame = requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    function (callback) { setTimeout(callback, 16); };

Here’s where it’s specified.

The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:

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

See also the note at the bottom of the section, which directly addresses your question!

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

Ry-
  • 218,210
  • 55
  • 464
  • 476