Why does "[] == 0" return true, and "[]" true, and "0" false?
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
room
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"
https://es5.github.io/#x11.9.3
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
- 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 :)
source to share