Reputation: 52952
alert (0 == ''); // true
alert (0 == '0'); // true
I understand that == in javascript performs a conversion and then checks for equality, but how does it perform the conversion in the statements above? Does it convert 0 to '' or '' to 0? Or something else perhaps? Is there a spec somewhere that explains the implementation?
Upvotes: 0
Views: 87
Reputation: 285077
The specification is ECMAScript.
The algorithm is given in 11.9.3, The Abstract Equality Comparison Algorithm.
For both, "Type(x) is Number and Type(y) is String, [] return the result of the comparison x == ToNumber(y)"
ToNumber is in 9.3. MV stands for "mathematical value." I think the rules that apply are:
In other words, an empty string converts to 0, and '0' is just a regular decimal in string form.
Upvotes: 1
Reputation: 322622
It uses the Abstract Equality Comparison Algorithm.
Specifically for your example
If
Type(x)
isNumber
andType(y)
isString
, return the result of the comparisonx == ToNumber(y)
.
So then you'll end up with:
0 == 0
...in both cases because an empty string converts to the number 0
, and a numeric string converts to the number given.
From 9.3.1 ToNumber Applied to the String Type:
A StringNumericLiteral that is empty or contains only white space is converted to
+0
Since we're now doing a comparison of the same Type on the second pass, it will do the following:
If
Type(x)
is the same asType(y)
, then... If
Type(x)
isNumber
, then... If
x
is the sameNumber
value asy
, returntrue
.
To test a toNumber
conversion, you can use the unary +
operator.
console.log( +'' ); // 0
console.log( +'0' ); // 0
Upvotes: 5
Reputation: 755587
How this is converted is covered in section 11.9.3 in the EMCA 262 spec. The following rule is applicable to this scenario (where x == y
)
if Type(x) is Number and Type(y) is String then convert y to a number and compare
In both examples here JavaScript will convert y
to a number and both will result in 0
so the comparison is true
Upvotes: 1