Why does 2 && 3 results in 3 (javascript)? [duplicate]

ぐ巨炮叔叔 提交于 2019-12-01 17:07:38

If the left hand side of && evaluates as a false value, the whole expression evaluates as the left hand side.

Otherwise it evaluates as the right hand side.

2 is a true value, so 2 && 3 is 3.

For comparison, try console.log(0 && 1) and console.log(false && "something").

The && logical operator will return the last value if all other values are truthy else it will return the first non truthy value.

So in your case since 2 is truthy then it will evaluate 3 and since that is truthy it will be returned.

Same way 2 && 0 && 4 will return 0 as it is a non truthy value.

Logical Operator

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

&& has to evaluate all expressions. 2 && 3 will first evaluate the “truthiness” of 2 which is a true value but then it has to evaluate 3 as well. That last evaluated value is then returned. If at least one value is non-truthy then the first such value is returned instead.

|| on the other hand returns the first truthy expression or the last non-truthy if there are no truthy expressions.

The reason why && returns the last possible value is that it simply has to check all expressions in order to return a result. || doesn’t have to do that. If the first expression for || is true it ignores all further ones. Likewise if the first expression for && is false it ignores all further ones (see short-circuiting in logical operators).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!