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?

2
  • Identity comparison. They're referencing two different objects. Commented Oct 13, 2013 at 5:05
  • two different objects are never equal. Commented Oct 13, 2013 at 5:07

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.
I agree with you. Thus the only way would be to compare the properties of variables recursively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.