I wanted further clarification on something.
Consider this:
var a = 42;
var b = \"abc\";
var c = null;
a || b; // 42
a && b; // \
What exactly is taking place when you chain the values?
In the first expression (&&) all the values must be truthy in order for the conditional test to pass. Assuming all values to be truthy the interpreter would evaluate all the values and the conditional test would pass. Otherwise it would evaluate up to the first falsey value and the conditional test would fail.
In the second expression (||) only one value must be truthy in order for the conditional test to pass. Assuming at least one value to be truthy the interpreter would evaluate up to the first truthy value and the conditional test would pass. Otherwise it would evaluate all the values and the conditional test would fail.
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.