Reputation: 1839
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?
Upvotes: 0
Views: 680
Reputation: 7285
In JavaScript, there are truthy and falsy values. The falsy values are
false
0
(the number zero), ""
or ''
(the empty string), undefined
and null
.All other values are truthy.
This is how the &&
operator works in JavaScript:
Let's take a look at your examples:
The 1
in 1 && 2
is truthy, so 2
is evaluated and returned as the value of the expression.
The false
in false && X
is falsy, so it is returned as the value of the expression. The second operand (X
) will not be evaluated.
The true
in true && X
is truthy, so the second operand is evaluated, which throws an error, because there is no X
.
This behavior is very useful if you want to have a fallback value:
function logName (options) {
const name = options.name || 'Default name';
console.log(name);
}
logName({ name: 'foo' }); // logs 'foo'
logName({ name: '' }); // logs 'Default name'
logName({}); // logs 'Default name'
Upvotes: 2
Reputation: 8921
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.
Upvotes: 4
Reputation: 2537
So consider the following statement: A && B
. What the &&
operator does here is return A
only if its value is false
otherwise it returns B
. That’s how the AND operator works in JavaScript and most other languages for that matter.
So this explains the first 2 lines of code. In the third line, the statement should return the B
variable which is X
in here. However X
seems to be an undeclared variable so the console raises an error.
Upvotes: 1