Tony Ng Tony Ng - 3 years ago 168
Javascript Question

Logical Operators (AND Operators)

I came across the following logical operators workaround but could not comprehend the logic behind:

console.log(1 && 2)
will get you

console.log(false && X)
will get you

console.log(true && X)
will get you
UncaughtReferenceError:X is not defined

Anyone can explain the answer?

Answer Source

Look at the documentation for the && operator:

&&; 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download