0

I saw this on the underscore.js docs under _.isEqual. Why is this the case?

var moe   = {name: 'moe', luckyNumbers: [13, 27, 34]};
var clone = {name: 'moe', luckyNumbers: [13, 27, 34]};
moe == clone;
=> false

Is it because strings and numbers aren't objects so they can be compared, but JS doesn't allow you to compare Arrays or Object Literals which are Objects?

Verdi Erel Ergün
  • 1,021
  • 2
  • 12
  • 20

2 Answers2

3

Object literal always defines a new object and thus variables moe and clone refer to different objects.

An expression comparing Objects is only true if the operands reference the same Object

read more about comparison

also this post has a nice asnwer with a deep "look-alike" comparison function

Community
  • 1
  • 1
Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
0

Use JSON.stringify property:

JSON.stringify(moe) === JSON.stringify(clone)

Note: Order of the properties is very important. In this case, properties of moe should be in the same order as properties of clone or vice-versa.

Joke_Sense10
  • 5,341
  • 2
  • 18
  • 22
  • 2
    That will work assuming it's an exact copy, but will fail if the keys are out of order, such as `clone = {luckyNumbers: [13, 27, 34], name: 'moe'}`. The objects are still effectively the same (order doesn't technically matter), but would fail the JSON test. The only true way to test equality is to recursively iterate over the entire object. – Dan Hlavenka Oct 13 '13 at 05:22
  • I agree with you. Thus the only way would be to compare the properties of variables recursively. – Joke_Sense10 Oct 13 '13 at 05:28