Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Object() != Object() in JavaScript? [duplicate]

Tags:

javascript

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?

like image 665
Afshin Mehrabani Avatar asked Sep 01 '14 19:09

Afshin Mehrabani


2 Answers

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

like image 115
jonasnas Avatar answered Oct 03 '22 21:10

jonasnas


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.
like image 41
Rahul Tripathi Avatar answered Oct 03 '22 21:10

Rahul Tripathi