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
4 Answers
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
returnsexpr1
if it can be converted tofalse
; otherwise, returnsexpr2
. Thus, when used with Boolean values,&&
returnstrue
if both operands are true; otherwise, returnsfalse
.
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
版权声明:本文标题:javascript - Why does 1 && 2 return 2? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742119832a2421643.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论