I was rambling with JavaScript code in my application today when I observed something strange.
var someVar = 25;
var anotherVar = 50;
var out = (anotherVar == 50 && someVar);
console.log(out) // outputs 25 and not true or false;
Any idea what's happening?
0 and 1 are type 'number' but in a Boolean expression, 0 casts to false and 1 casts to true . Since a Boolean expression can only ever yield a Boolean, any expression that is not expressly true or false is evaluated in terms of truthy and falsy. Zero is the only number that evaluates to falsy.
In programming languages value of True is considered as 1. whereas false is zero. therefore In Boolean algebra True + False=1+0=1.
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
When converting to bool, the following values are considered false : the boolean false itself. the integer 0 (zero) the floats 0.0 and -0.0 (zero)
As stated on MDN's Logical Operators page, the &&
operator:
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values,
&&
returns true if both operands are true; otherwise, returns false.
In your case, expr1 (anotherVar == 50
) is true (not false), so it returns expr2 (someVar
), which is 25
.
It doesn't return true
or false
because expr2 isn't a Boolean value.
The ECMA-262 Specification notes:
The value produced by a
&&
or||
operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With