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?
Objects are compared by reference. And two references are equal only if they point to the same object.
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).Object.is, which will also test for identity on objects, only strict, and not broken like ===...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 ensure42is equivalent toNumber(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
undefinedvalue they have the same properties all of which are considered recursively equivalent.
a, with the same value,1. Though, some libraries, such as Underscore, do define functions for this purpose.