Reputation: 11
In the ES5 spec, clauses 11.9.3.4-5 say:
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
How I understand this is:
"" is coerced to number and becomes 0 -> "0"==0
then recursively "0" is coerced to number and becomes also 0 -> 0==0
so the output must be true.
but it is false.
can you explain why?
console.log("0"=="")
Upvotes: 0
Views: 120
Reputation: 369458
The very first clause in 7.12.4 Abstract Equality Comparison is:
- If Type(x) is the same as Type(y), then
a. Return the result of performing Strict Equality Comparison x === y.
7.12.5 Strict Equality Comparison reads, in its entirety:
- If Type(x) is different from Type(y), return false.
- If Type(x) is Number or BigInt, then
a. Return ! Type(x)::equal(x, y).- Return ! SameValueNonNumeric(x, y).
Since the types of "0"
and ""
are both String, neither case #1 nor case #2 applies, so we go to 7.2.12 SameValueNonNumeric(x, y):
- Assert: Type(x) is not Number or BigInt.
- Assert: Type(x) is the same as Type(y).
- If Type(x) is Undefined, return true.
- If Type(x) is Null, return true.
- If Type(x) is String, then.
a. If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false.- If Type(x) is Boolean, then a. If x and y are both true or both false, return true; otherwise, return false.
- If Type(x) is Symbol, then a. If x and y are both the same Symbol value, return true; otherwise, return false.
- If x and y are the same Object value, return true. Otherwise, return false.
It should be easy to see that case #5 applies here:
- If Type(x) is String, then.
a. If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false.
It should also be easy to see that "0"
and ""
are not exactly the same sequence of code units, since they have neither the same length nor the same code units at corresponding indices.
Therefore, the result is false
, as per the second alternative of 7.2.12, clause 5, subclause a.
Upvotes: 1
Reputation: 370779
"0"
is a string. So is ""
. No type coercion is involved.
The string composed of 0
(a single character, character code 48) is not equivalent to the empty string.
If the '0'
was 0
instead, the process would occur as you're describing it:
console.log(0 == "")
The empty string gets turned into a number - 0 - and then 0 === 0
evaluates to true
.-
(but I'd suggest never using sloppy equality regardless - always use strict equality and you won't have to worry about any of this silliness)
Upvotes: 1