-3

I am not able to understand how does javascript handles object equality. Please can anybody explain me the below output?

1. var x = 3; 2. var y = 3; 3. var obj1 = {}; 4. var obj2 = {}; 5. var obj3 = obj1; 6. x == y 7. x === y 8. obj1 == obj2 9. obj1 === obj2 10. obj1 == obj3 11. obj1 === obj3

Output:

  1. true

  2. true

  3. false

  4. false

  5. true

  6. true

Rush W.
  • 1,321
  • 2
  • 11
  • 19
  • 2
    [Possible dupe](https://stackoverflow.com/q/11704971/5267751). – user202729 Mar 23 '18 at 07:34
  • Possible duplicate of [Why are two identical objects not equal to each other?](https://stackoverflow.com/questions/11704971/why-are-two-identical-objects-not-equal-to-each-other) – Dario Mar 23 '18 at 07:45

1 Answers1

1

When you compare objects using either == or ===, the comparison is only true if the objects are the same object, not merely identically-constructed objects, but the very same object.

If you want to compare objects for whether they are identically constructed, you might want to look into something like LoDash: https://lodash.com/docs/4.17.5

Particular relevant here is the _.isEqual() function: https://lodash.com/docs/4.17.5#isEqual

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • But if i try to check `[] == []` , it also returns **false**. Are arrays = object in javascript? – Rush W. Mar 23 '18 at 07:46
  • 1
    You can think of arrays as a special class of objects, yes, and that's certainly true for how they're compared. LoDash's `_.isEqual()` function will handle such array comparisons as well. – kshetline Mar 23 '18 at 07:48