kanchan sharma
kanchan sharma

Reputation: 43

Why does 1 && 2 return 2?

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

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

Upvotes: 3

Views: 12385

Answers (4)

dagelf
dagelf

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

coder87
coder87

Reputation: 101

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

Upvotes: 0

eavichay
eavichay

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

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

Upvotes: 3

tklg
tklg

Reputation: 2642

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.

Upvotes: 1

Related Questions