Why does "[] == 0" return true, and "[]" true, and "0" false?

If I execute the following lines in the browser console

!![] //--- returns true
!!0 //--- returns false


I get that []

and 0

have different booleans.

I do not understand why

[] == 0 //--- returns true


returns true


What am I missing?


source to share

2 answers

Remember that an array is an object and 0 is a number.

And as "user2864740" said ..

1) When you do

!![] //--- returns true
!!0 //--- returns false


You are doing the so called "ToBoolean" conversion



The result is false if the argument is +0, -0, or NaN; otherwise, the result is correct.

Object (our [])

always true

2) But when you use == you are doing a so called "Equality comparison"


It's a little more complicated here, but to understand what's going on you have to remember that == is doing a type coercion (so you can compare oranges to apples :))

First of all, the compiler converts [] to some primitive type.

If type (x) is either a string or a number and type (y) is an object, returns the result of the comparison x == ToPrimitive (y).

How ToPrimitive works, this is an article article :) but it's easy to remember that the closet primitive type for an array is a string. The array will be converted to an empty string.

[]. toString () === ""

So now we need to compare the empty string and the number 0

"" == 0   // true


Hmmm. The way it is. But why? Remember that when you are comparing an Equality Comparison number and a string

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

So try converting an empty string to a number

Number("") === 0


And in the end

0 === 0


I hope this explains something :)



JavaScript will probably convert the array to a number:
!!Number([]) // false

Number([]) == 0 // true



All Articles