28

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

Can someone explain why ?

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Does this answer your question? [Why doesn't equality check work with arrays](https://stackoverflow.com/questions/30820611/why-doesnt-equality-check-work-with-arrays) – Nico Haase Feb 03 '22 at 13:07

4 Answers4

20

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
otakustay
  • 11,817
  • 4
  • 39
  • 43
9

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.

RaiBnod
  • 2,141
  • 2
  • 19
  • 25
5

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

xdazz
  • 158,678
  • 38
  • 247
  • 274
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.

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110