JavaScript implicit coercion of empty arrays

JavaScript implicit coercion of empty arrays

example:

[] == ![]
        //toBoolean [1]
[] == !true
[] == false
//loose equality round one [2]
//toPrimitive([]) [3]
"" == false
//loose equality round two
//toBoolean("") [4]
false === false
true

explanations:

1)

First there is operator precedence so ! evaluates before ==

Negating something calls the internal toBoolean method onto that “something” first. In this case this is an Object (as Arrays are Objects) and for that it always returns true which is then negated.

2)

Now it’s up to loose equalities special behaviour:

If A is an Object ( Arrays are Objects ) and B is a Boolean it will do:

ToPrimitive(A) == B

3)

ToPrimitive(A) attempts to convert its Object argument to a primitive value, by attempting to invoke varying sequences of A.toString and A.valueOf methods on A.

Converting an Array to its primitive is done by calling toString ( as they don’t have a valueOfmethod) which is basically join(",").

4)

Well empty Strings are falsy

Where did I get it wrong?

At step 1. Negating something does not call toPrimitive but toBoolean …

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s