JavaScript implicit coercion of empty arrays

JavaScript implicit coercion of empty arrays


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



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.


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


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(",").


Well empty Strings are falsy

Where did I get it wrong?

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


Leave a Reply

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

You are commenting using your 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