8

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?

lukaszkups
  • 5,790
  • 9
  • 47
  • 85

3 Answers3

15

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
9

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.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
6

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

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75