Reputation: 43
Why does the expression 1 && 2
evaluate as 2?
console.log("1 && 2 = " + (1 && 2));
Upvotes: 3
Views: 12385
Reputation: 1739
Because its and
, all the values need to be evaluated only up to the first 0, and the value of the last evaluation is returned, and it's the last one.
Although not directly relevant here, note that there's a difference between bitwise
and logical
operators. The former tests bits that are the same and only return those, the latter reduces to only true
(!=0) or false
(=0), so contrary to intuition, bitwise AND
and AND
are not interchangable unless the values are exactly 0
or 1
.
Upvotes: 0
Reputation: 101
According to this page:
AND returns the first falsy value or the last value if none were found. OR returns the first truthy one.
For multiple operators in same statement:
precedence of the AND && operator is higher than OR ||, so it executes before OR.
alert( 5 || 1 && 0 ); // 5
Upvotes: 0
Reputation: 517
&& (and operator) returns the last (right-side) value as long as the chain is "truthy".
if you would try 0 && 2 -> the result would be 0 (which is "falsy")
Upvotes: 3