`[1] == [1]` returns "false" and `[1] == 1` returns" true "?
I found this strange behavior in javascript
.
var v1 = [1];
var v2 = [1];
v1 == v2 // false
v1 == 1 //true
[1] == [1] // false
1 == [1] // true
why does it [1] == [1]
return false
and [1] == 1
return true
?
spec says that if two operands ==
are of the same type of each other (for example, in the case [1] == [1]
where both of them are a type Object
), then ==
behaves exactly the same as ===
. These two arrays are not the same object, so it is returned false
. Note:
var v1 = [1];
var v2 = v1;
v1 == v2; // true
When the operands are of different types, they are both coerced. In the case, 1 == [1]
Rule 10 from the above link is applied first and the array is converted to the primitive that's it toString()
, which returns it '1'
. Then rule 6 (string '1'
to number conversion 1
) is applied and the comparison becomes 1 == 1
, and finally they are of the same type and are compared with ===
. Obviously 1 === 1
true.