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.
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.
&&
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); };
The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:
- 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).
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.