How to compare the values of two javascript objects?

How to compare the values of two javascript objects?

When it comes to comparing JavaScript variables it is very easy, however, objects do not behave the same way, why is this?

Subscribe to my newsletter and never miss my upcoming articles

When it comes to comparing Javascript variables it is very easy, a simple statement like this will do the job:

if(a === b) { doSomething() }

What if you want to compare to objects? Why not just do this:

if (myObject === yourObject) { doSomething() }

Well, that will not work because the if statement will always return false even if the objects are exactly the same! Why is this?

Here is why: Primitive Types vs Reference Types.

In Javascript, we have two types of memory allocation. I won't go into details you can read more about it here. I will stick to the simple answer:

The primitive types, keeping it simple, are number, string, boolean, undefined and null. A full list can be found here. When you create a primitive type, the value and the reference is stored in the memory. So whenever you compare two primitive types the actual value gets compared.

Reference types, to keep it simple, are Objects, Functions and Arrays. Collectively known as objects. More information can be found here. When you create a reference type, the value and the reference is stored in the memory. However, when you compare two reference types the actual value does not get compared, only the reference to the memory location.

So back to our question: how do you compare the values of two JavaScript objects?

So now if you do the following:

const myObject = { name : 'Dylan' }
const yourObject = { name: 'Dylan' }

if(myObject === yourObject) { doSomethig() }
//always returns false

This happens because the variables are only pointing to the memory location, and they are stored in two different locations. Meaning they are not the same!

How do we work around this?

The answer might surprise you!

const myObject = { name : 'Dylan' }
const yourObject = { name: 'Dylan' }

if(JSON.stringify(myObject) === JSON.stringify(yourObject)) { doSomethig() }
//always returns true

//OR

const myObject = { name : 'Dylan' }
const yourObject = { name: 'Mike' }

if(JSON.stringify(myObject) === JSON.stringify(yourObject)) { doSomethig() }
//always returns false

See what we did there? We simply turned both objects into strings, meaning primitive types, so now the equality operator will work as intended.

Viola!

Side Note:

const myObject = { name : 'Dylan' }
const yourObject = myObject;
yourobject.name = "Mike";

if(myObject === yourObject) { doSomethig() }
//always returns true

The above piece of code will always return true when comparing the two objects, because directly assigning two object to one another will point both of them to the same memory location! Thus myObject name value will also change.

 
Share this