Why is Object ()! = Object () in JavaScript?

So the question is, two identical 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 is the reason for this strange behavior?

+5
source share
3 answers

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

+8
source

Objects are referenced, and when you compare two links, they return false.

another answer (given by Eamon Nerbonn) has a very important point:

Objects are considered equivalent if

  • They are exactly equal for === (String and Number are first unpacked to ensure 42 equivalent to Number(42) )
  • either they are dates and have the same valueOf()
  • either they are of the same type, not null and ...
    • they are not objects and are equal to == (captures numbers / strings / booleans)
    • or, ignoring properties with an undefined value, they have the same properties, all of which are considered recursively equivalent.
+2
source

The same applies to arrays ([] === []) //returns false

And NaN is also a special meaning that never coincides with itself.

NaN === NaN //False

+1
source

Source: https://habr.com/ru/post/1201594/


All Articles