5

So the question is that two same objects are not equal in JavaScript, let's say:

Object() == Object()

or even:

[{a: 1}, {a: 2}].indexOf({a: 1}); //returns -1 not found

What's the reason of this strange behavior?

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201

3 Answers3

8

Objects are compared by reference. And two references are equal only if they point to the same object.

jonasnas
  • 3,540
  • 1
  • 23
  • 32
  • Is that a correct behavior? Do we have the same behavior in other languages such as Python? – Afshin Mehrabani Sep 01 '14 at 19:19
  • 2
    @AfshinMehrabani yep. in Python ``The "is" operator tests object identity. Python tests whether the two are really the same object (i.e., live at the same address in memory).`` – doniyor Sep 01 '14 at 19:23
  • To prevent confusion: In JS You might stumble on `Object.is`, which will also test for identity on objects, only strict, and not broken like `===`... – Willem D'Haeseleer Sep 01 '14 at 19:33
2

Objects are reference and when you compare two reference they return false.

The other answer(given by Eamon Nerbonne) here has a very relevant point:

Objects are considered equivalent when

  • They are exactly equal per === (String and Number are unwrapped first to ensure 42 is equivalent to Number(42))
  • or they are both dates and have the same valueOf()
  • or they are both of the same type and not null and...
    • they are not objects and are equal per == (catches numbers/strings/booleans)
    • or, ignoring properties with undefined value they have the same properties all of which are considered recursively equivalent.
Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

Same applies for Arrays ([] === []) //returns false

And NaN is a special value as well which is never equal to itself.

NaN === NaN //False

Kiba
  • 10,155
  • 6
  • 27
  • 31