The following comparisons all return false in javascript:
[]===[]
[]==[]
{}==={}
{}=={}
[0]===[0]
[0]==[0]
However the following return true:
[0]=='0'
[0]==0
[]==false //(and all other == that were exampled above)
What is the reason for this? Especially the difference between [0]!=[0] and [0]==0
Fiddle: http://jsfiddle.net/vnBVj/
This is due to the confusing rules, how javascript does type coercion. You can read about this in §11.9.3 of the EcmaScript 5 spec.
Two Objects (which Arrays are too) are never equal, thus all your comparisons in the first block yield false (§11.9.3.1.c.vi)
The second block is more difficult:
First thing to know is, that
==uses type coercion to compare the operands.When a comparison has a Boolean involved, this one is first coerced to a number.
after that Objects are coerced to their primitive values by calling
Object.prototype.toStringThen the string is coereced to to a number (
""becomes0)yielding true. By applying the same rules, you can see why your other examples also yield true.
Note that
===never causes type coercion, but checks for correct types first and yields false if they are not equal! Only if the types are equal, it compares the actual values. So this method of comparison is far more reliable than==.