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.
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 ensure42
is 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
undefined
value they have the same properties all of which are considered recursively equivalent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With