DEV Community

loading...

Discussion on: Comparing Values of Objects in JavaScript 🧭

Collapse
pentacular profile image
pentacular

Because primitive data types are compared by their values, while objects in JavaScript are compared by their reference, so, the simple equality operator will only check if the location of the two objects is the same or not.

Objects in Javascript are compared by their value, just like any other value -- there is no 'object reference' in javascript.

What you've missed here is that the properties associated with an object are not part of the object's value.

let areEqual = (object1, object2) => {
return
object1.key1 === object2.key1 &&
object1.key2 === object2.key2 &&
object1.key3 === object2.key3 //and so on
}

With this code you're not checking to see if the object's are equal -- you're checking to see if two objects have properties with the same names and values.

This should also make it clear that this isn't how object equality works, because if it were, you'd need to recurse through each of those properties using areEqual, rather than using === to compare object values. :)

So, let's be clear.

  1. a === b compares two object values, just like it does non-object values.
  2. object values are independent of the properties associated with the object.
  3. testing to see if objects have equivalent properties associated needs to consider deep and shallow equivalence, and is not the same as comparing value.

As we can see, that code is just a single line, and we can use this function with any two objects.

Not exactly -- JSON.stringify won't work on objects with cyclic property structures.

e.g.

const a = {};
a.a = a;
JSON.stringify(a); // boom

JSON.stringify also only produces (unsurprisingly) things that can be represented in JSON, which excludes a number of javascript types --- for example, undefined and Symbol.

It will also lose information such as prototypical inheritance structures.

Collapse
nemo011 profile image
Nemo Author

Thank you a lot for sharing so much. I really appreciate it. And also learnt a lot l! Thanks again for correcting me. 😊