How To Check If Two Objects Are Equal

If this question comes up you must ask yourself, what are we going to actually check for equality? Two objects or the properties of two objects?

If you have two objects are pointing to the ame location in memory then yes, they are considered equal. On the other hand, if they have the the same properties with the same values but are pointing to different locations in the memory, then they will not appear as equal.

Let me explain in simple code:

var firstObject= {
    name: "First",
};

var secondObject= {
    name: "First",
};

var thirdObject = firstObject;

console.log(firstObject === secondObject); //false

console.log(firstObject === thirdObject ); //true

Even though the object’s property name has the same value, the objects are not equal since they point to another location in the memory.
To give a bit more details for extra credit you can mention that the === or == operators will compare primitives like numbers, strings etc by their value, while objects, arrays, dates are compared by reference.

How to check if two objects have the same properties?

Here there are a few solution.
In an ideal situation, if both objects have the same order for their property, you can simply use stringify

Lodash is also a valid method!

const child1 = { name: 'Brad' };
const child2 = { name: 'Brad' };

// Only JavaScript
JSON.stringify(child1) === JSON.stringify(child2); // true

// Importing Lodash
_.isEqual(child1, child2); // true

But what about if the properties are not in the same order?
In that case stringify will not work, while lodash will:

const child1 = { 
   name: 'Brad',
   age: 5
};
const child2 = { 
   age: 5
   name: 'Brad' 
};

// Only JavaScript
JSON.stringify(child1) === JSON.stringify(child2); // false

// Importing Lodash
_.isEqual(child1, child2); // true

Performance considerations:

Lodash will be faster than stringify. Stringify will have to serialize the entire object no matter if it matches or not, while lodash’s isEqual can interrupt the execution once it finds a mismatch.

So, in this case, importing lodash will actually prove to be a better tradeoff. If you don’t need the library for anything else you can just borrow the function from it, but make sure to satisfy the license.

Leave a Reply