Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Javascript giving result as Number instead of True/False for expression? [duplicate]

Tags:

javascript

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?

like image 571
Snehal Masne Avatar asked Dec 18 '14 13:12

Snehal Masne


People also ask

What is result of True == 1 in JavaScript?

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.

Why is True False 1?

In programming languages value of True is considered as 1. whereas false is zero. therefore In Boolean algebra True + False=1+0=1.

What will the JavaScript expression 0 == false evaluate to?

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.

Does the integer 0 == 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)


1 Answers

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.

like image 69
James Donnelly Avatar answered Oct 25 '22 17:10

James Donnelly