Why the console shows "2" and "false" in this expressions?
var a = '' || 0 || 2 || true || false;
var b = 3 && true && false && null;
console.log (a,b);
Why the console shows "2" and "false" in this expressions?
var a = '' || 0 || 2 || true || false;
var b = 3 && true && false && null;
console.log (a,b);
You got those results because it's logical comparison here, using logical operators &&
and ||
, if you take a look at MDN Specification of Logical Operators, you will see that:
Logical OR (||): Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand can be converted to true; if both can be converted to false, returns false.
Logical AND (&&): Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands can be converted to true; otherwise, returns false.
So in your case:
For the first expression:
var a = '' || 0 || 2 || true || false;
It will return 2
because it's the first oprand that's evaluated to true
.
And for the second one:
var b = 3 && true && false && null;
It will return false
as one of its operand is false
.