30

I have come across a situation where [] == [] is false in Javascript.

Can someone explain why ?

1

4 Answers 4

22

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
Sign up to request clarification or add additional context in comments.

Comments

10

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.

Comments

5

Because they are not same object, different object never identical equal, so the result is false.

Comments

0

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.

1 Comment

so how do you compare

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.