NibblyPig
NibblyPig

Reputation: 52952

How does JavaScript convert types when comparing with == ?

alert (0 == ''); // true
alert (0 == '0'); // true

JSFiddle Proof

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

Answers (3)

Matthew Flaschen
Matthew Flaschen

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:

  • "The MV of StringNumericLiteral ::: [empty] is 0."
  • "The MV of StrNumericLiteral ::: StrDecimalLiteral is the MV of StrDecimalLiteral"

In other words, an empty string converts to 0, and '0' is just a regular decimal in string form.

Upvotes: 1

user113716
user113716

Reputation: 322622

It uses the Abstract Equality Comparison Algorithm.

Specifically for your example

If Type(x) is Number and Type(y) is String, return the result of the comparison x == 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 as Type(y), then

... If Type(x) is Number, then

... If x is the same Number value as y, return true.


To test a toNumber conversion, you can use the unary + operator.

console.log( +'' );   // 0
console.log( +'0' );  // 0

Upvotes: 5

JaredPar
JaredPar

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

Related Questions