I came across the following logical operators workaround but could not comprehend the logic behind:
console.log(1 && 2)
will get you 2
console.log(false && X)
will get you false
console.log(true && X)
will get you UncaughtReferenceError:X is not defined
Anyone can explain the answer?
Best Answer
Look at the documentation for the
&&
operator:In the first example, you provide the numbers 1 and 2 as the operands. 1 cannot be converted to
false
, therefore the second operand, which happens to be 2, is returned.The two last examples are fairly straightforward, as booleans are involved. If either operand is false, you get back
false
. The reason only the third one gives you an error is because in the second, the second operand (X
) is never checked due to short-circuiting. Short-circuiting means that once JS sees that the first value isfalse
, it does not even bother to check the other value. JS seesfalse
as the first operand and immediately returns.