I was asked in an interview that what would be logged by the following:
console.log(1||2);//logs 1
console.log(1&&2);//logs 2
DEMO
console.log(1||2,1&&2)
But Why? How are they evaluated?
I am sorry if its a duplicate :(
I was asked in an interview that what would be logged by the following:
console.log(1||2);//logs 1
console.log(1&&2);//logs 2
DEMO
console.log(1||2,1&&2)
But Why? How are they evaluated?
I am sorry if its a duplicate :(
That is how those logical operators are implemented in Javascript.
Intuition behind their working I think can be explained by looking at how short circuit evaluation works.
For example with ||, if you know the left hand side is truthy there is no need to check the right hand side (because the result will be true anyway) - so it directly returns what's on the left hand side.
For &&, it is not enough that left hand side is truthy, one must also check right hand side. If right hand side is also truthy it returns what is on the right hand side.
More details here.
One important thing in javascript is that everything (not only booleans) can be either truthy, or falsy. Everything except null
, undefined
, 0
and false
is truthy, these are falsy.
if(1) alert("truthy");
if(0) alert("falsy");
Now the logical operators are defined as:
||
: returns the left side if it is truthy, otherwise it returms the right side. That also works as expected with booleans:
false || false // false
false || true // true
0 /*falsy */ || 1 /*truthy*/ // 1
1 /*truthy*/ || 0 // 1
&&
: returns the first if it is falsy, otherwise the right one:
false && true // false
0 && 1 // 0
1 && 2 // 2