Why does 2 && 3 lead to 3 (javascript)?

When I type in the browser console:

console.log(2 && 3) 

it is always displayed with the second number (in this case 3):

 3 

Can someone explain to me why?

+8
javascript logic logical-operators
source share
3 answers

If the left side of && evaluates to false, the entire expression evaluates to the left side.

Otherwise, it is evaluated as the right side.

2 is the true value, therefore 2 && 3 is 3 .

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

+14
source share

&& & the logical operator will return the last value if all other values ​​are true, otherwise it will return the first value without truth.

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

The same path 2 && 0 && 4 will return 0 , as this is an impractical value.

Logical operator

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

+9
source share

&& must evaluate all expressions. 2 && 3 will first evaluate the β€œtruth” 2 , which is the true value, but then it must also evaluate 3 . Then the last evaluated value is returned. If at least one value is not true, then the first such value is returned instead.

|| , on the other hand, returns the first plausible expression or the last incorrect if there are no right expressions.

The reason && returns the last possible value is because it just needs to check all expressions to return the result. || shouldn't do that. If the first expression for || verily, it ignores all the others. Similarly, if the first expression for && false, it ignores all the others (see Short Circuit in Logical Operations).

+5
source share

All Articles