Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How type coercion happens when [] == false?

Tags:

javascript

ECMA script documentation says in abstract equality comparison alogorithm that,

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

So for instance, [] == false will be coerced like,

1.   [] == Number(false)
2.   [] == 0 //comparison happens here.

My question is, the coercion will be happened recursively until the two operands becomes primitive or not? How exactly the coercion happens here?

I presume the coercion will be repeated until the conversion of two operands to primitive, like below

1.   [] == Number(false)
2.   [] == 0
3.   ToPrimitive([]) == 0
4.   0 == 0 
5.   true

Is my presumption true? If not can anyone explain what is wrong here? Also how can I verify the result of ToPrimitive([]) is 0 in any browser's console ?

like image 666
Rajaprabhu Aravindasamy Avatar asked Feb 16 '16 13:02

Rajaprabhu Aravindasamy


1 Answers

Refer to the spec, the [] == false could be parsed as below form

ToNumber(ToPrimitive([])) == ToNumber(false)

Here are more details

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

[] == ToNumber(false)

If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison ToPrimitive(x) == y

ToPrimitive([]) == 0

According to the ToPrimitive algorithm, valueOf is called first. But since that returns an object, not a primitive value, toString will be called secondly, which returns a string '', empty string

If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y

ToNumber('') == 0

Then after ToNumber to 0. Compare to ToNumber(false) is also 0. As a result, they are same.

like image 118
zangw Avatar answered Oct 14 '22 00:10

zangw