I have come across a situation where [] == []
is false
in Javascript.
Can someone explain why ?
I have come across a situation where [] == []
is false
in Javascript.
Can someone explain why ?
Objects are equal by reference, []
is a new object with a new reference, the right hand []
is also a brand new object with a new reference, so they are not equal, just like:
var user1 = new User();
var user2 = new User();
user1 === user2; // Never true
Consider following two scenarios:
[] == []; // returns false
["foo"] == ["foo"]; // returns false
Here, two different objects are created & those two different instances created on different memory location will never be the same (object instances comparison compares memory addresses). Results false
in output.
But,
["foo"] == "foo"; // returns true
Here, ["foo"]
object type is implicitly gets converted into primitive type
. For now "foo"
on the right side is string
so it tries to convert it on string
(.toString(), since double equals allows coercion
) and compare "foo" == "foo"
, which is true
.
Conclusion: we compare object instances via the memory pointer/address or we can say references, and primitive types via the real value comparison.
Because they are not same object, different object never identical equal, so the result is false
.
See Object identity because both array create a new instance of array so comparing two different object is not equal. Your code is equivalent to:
var arr1 = [],
arr2 = [];
arr1 == arr2; // false
Two literals always evaluate to two different instances, which are not considered equal.