Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the expression "{} == true"?

Tags:

I try to understand the expression {} == true following the section 7.2.12 of doc Ecma-262.

  1. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y)

The result of ToNumber(true) is 1, then

{} == 1

  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.

  1. If hint is "string", then

    a. Let methodNames be «"toString", "valueOf"».

  2. 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)?

like image 282
zangw Avatar asked Dec 30 '15 08:12

zangw


Video Answer


1 Answers

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 be ToNumber(ToPrimitive({})) == ToNumber(true)?

Yes, that's exactly what it is.

like image 179
Felix Kling Avatar answered Dec 05 '22 22:12

Felix Kling