I am revisiting implicit coercion in javascript and realized that I have overlooked something and need clarification on it.
if
var a = "5";
var b = 5;
and a==b
will return true
.
But there are two possible ways a==b
could give true coercion right? It's either 5 == 5
, or '5' == '5'
. So which one is actually happening for the above example here?
The answer is in the Abstract Equality Comparison Algorithm in the spec, specifically:
- If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.
(The !
before ToNumber(x)
does not mean negation, it's a spec notation asserting that ToNumber(x)
will never result in an abrupt termination.)
It's a numeric comparison, "5"
is converted to 5
and then the comparison is done.