JavaScript Scalar Comparison

Question:

Explain, please, why out of the three alerts below, only the last one is executed? It seems like in all three cases there is a soft comparison for equality to true

if (true == "0") alert('Тру равно нулю!');

if ("0" == true) alert('Ноль равен тру');

if ("0") alert('Как бы тоже тру, или как?');

https://jsfiddle.net/z1xbshmk/

Answer:

It is worth referring to the specification
Evaluating EqualityExpression == RelationalExpression returns the left and right values ​​and applies the Abstract Equality Comparison to them.

The comparison x == y, where x and y are values, returns true or false . Such comparisons are made as follows:
If Type (x) is the same as Type (y) , then Strict Equality Comparison x === y is returned.
If x is null and y is undefined , return true .
If x is undefined and y is null , return true .
If Type (x) is Number and Type (y) is String , return the result of x == ToNumber (y) .
If Type (x) is String and Type (y) is Number , return the result of ToNumber (x) == y .
If Type (x) is Boolean , return the result of ToNumber (x) == y .
If Type (y) is Boolean , return the result of x == ToNumber (y) .
If Type (x) is one of the following: String , Number , or Symbol and Type (y) is Object , return the value of the expression x == ToPrimitive (y) .
If Type (x) is Object and Type (y) is one of the following: String , Number , or Symbol , return the value of the expression ToPrimitive (x) == y .
Return false .

Let's take a look at the first example:

true == "0"

This expression matches the branch

If Type (x) is Boolean , return the result of ToNumber (x) == y .

When reduced to a number, we get the expression: 1 == "0"
we get into the branch

If Type (x) is Number and Type (y) is String , return the result of x == ToNumber (y) .

When converted to a number, we get the expression: 1 == 0 and as a result: false .

The second case is similar.

Now let's look at the third case.

Let's go back to the spec :

The ToBoolean function is applied to the expression inside the brackets, which, in the case of a string, returns false if the string is empty (string length 0), and true otherwise.

Since "0" is not empty (line length 1), the condition is considered to be fulfilled.

Scroll to Top