So what exactly is happening when you use the &&
and ||
operators with chaining values
&&
is a binary operator, with one left-hand operand and one right-hand operand. The expression a && b && c && d && e
is parsed based on associativity rules so that it looks like this:
if (a && (b && (c && (d && e)))) {
Based on the semantics of &&
, if a
is falsy, the entire condition immediately evaluates to a
, which is falsy. If a
is truthy, then the expression evaluates to the right side, which is b && (c && (d && e)))
. In that case if b
is falsy, then that sub-expression, and thus the entire expression, immediately evaluates to b
, which is falsy; if b
is truthy, then that sub-expression evaluates to its right side, which is c && (d && e)
, and the process continues.
The net result is the intuitive behavior that for the entire expression to be falsy, and therefore for the if
branch to not be taken, it suffices for any of the variables to be falsy. The evaluation will "short-circuit"--resulting in falsy--as soon as any falsy variable is encountered. For the entire expression to be truthy, and therefore for the if
branch to be taken, all the variables must be truthy.
For ||
, the logic is reversed. For the entire expression to be truthy, and therefore for the if
branch to be taken, it suffices for any of the variables to be truthy. The evaluation will "short-circuit"--resulting in truthy--as soon as the first truthy value is encountered. For the entire expression to be falsy, and therefore for the if
branch not to be taken, all the variables must be falsy.
You Don't Know JS has a good explanation too.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…