I came across the following logical operators workaround but could not comprehend the logic behind:
console.log(1 && 2)
console.log(false && X)
console.log(true && X)
UncaughtReferenceError:X is not defined
Look at the documentation for the
&&; Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
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 is
false, it does not even bother to check the other value. JS sees
false as the first operand and immediately returns.