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?

8
  • 2
    Those are two similar objects, they certainly are not the same. Commented Sep 1, 2014 at 19:13
  • 1
    Maybe that helps: stackoverflow.com/questions/201183/… Commented Sep 1, 2014 at 19:16
  • @Musa any more clues? Commented Sep 1, 2014 at 19:16
  • 1
    @AfshinMehrabani There isn't a predefined way to determine the similarity or "deep equality" of 2 objects -- e.g., they both only have 1 property, a, with the same value, 1. Though, some libraries, such as Underscore, do define functions for this purpose. Commented Sep 1, 2014 at 19:18
  • What's the reason of this strange question ? Commented Sep 1, 2014 at 19:20

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is that a correct behavior? Do we have the same behavior in other languages such as Python?
@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).
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 ===...
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.

Comments

1

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

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

NaN === NaN //False

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.