Skip to content Skip to sidebar Skip to footer

Why Does 2 && 3 Results In 3 (javascript)?

When I type in browser's console: console.log(2 && 3) it results always with second number (in this case 3): 3 Can someone explain me why?

Solution 1:

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

Solution 2:

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.

Solution 3:

&& 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).

Post a Comment for "Why Does 2 && 3 Results In 3 (javascript)?"