I try to understand the expression {} == true
following the section 7.2.12
of doc Ecma-262
.
- If Type(y) is Boolean, return the result of the comparison
x == ToNumber(y)
The result of ToNumber(true)
is 1
, then
{} == 1
- If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison
ToPrimitive(x) == y
.
I am confused at the ToPrimitive({})
now.
If hint is "string", then
a. Let methodNames be «"toString", "valueOf"».
Else,
a. Let methodNames be «"valueOf", "toString"».
Should ToPrimitive({})
be interpreted as {}.toString()
or {}.valueOf()
?
Suppose the toString()
is called.
If Type(x) is String and Type(y) is Number, return the result of the comparison
ToNumber(x) == y
So {} == true
could be ToNumber(ToPrimitive({})) == ToNumber(true)
?
The spec says:
When
ToPrimitive
is called with no hint, then it generally behaves as if the hint were Number.
Hence, according to the ToPrimitive
algorithm, valueOf
is called first. But since that returns an object, not a primitive value, toString
will be called second, which returns a string.
So
{} == true
could beToNumber(ToPrimitive({})) == ToNumber(true)
?
Yes, that's exactly what it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With