admin管理员组

文章数量:1323737

Why does the expression 1 && 2 evaluate as 2?

console.log("1 && 2 = " + (1 && 2));

Why does the expression 1 && 2 evaluate as 2?

console.log("1 && 2 = " + (1 && 2));

Share Improve this question edited Oct 15, 2017 at 19:31 Master Yoda 4,42212 gold badges45 silver badges81 bronze badges asked Oct 15, 2017 at 19:06 kanchan sharmakanchan sharma 431 gold badge1 silver badge5 bronze badges 1
  • 1 It's called Boolean shortcut's. You can do similar things with ||. eg.. 0 || 1 || 2" would return 1, where 0 && 1 && 2` would return 0. This is because in the first example || when it hits 1, the OR condition is met, it need not go any further and short circuit the rest. Where with the AND &&, the first condition make the and impossible so short circuits the 1 & 2.. – Keith Commented Oct 15, 2017 at 19:23
Add a ment  | 

4 Answers 4

Reset to default 3

&& (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")

https://developer.mozilla/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators

According to MDN:

expr1 && expr2 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.

Because 1 can be evaluated to true, 1 && 2 returns 2.

According to this page:

Why 1 && 2 == 2

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

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.

本文标签: javascriptWhy does 1 ampamp 2 return 2Stack Overflow