How to check if two objects are equal in JavaScript?

Published March 18, 2021

To check if two objects are equal, you can first make both the objects into a JSON string using the JSON.stringify() method and then check to see if the string representation of both the objects is equal in JavaScript.

For example, let's say we have 2 objects with a property called name and value of John Doe like this,

// 2 objects with same the property and values
const obj1 = { name: "John Doe" };
const obj2 = { name: "John Doe" };

// Check if 2 objects are equal using
// the JSON.stringify() method
JSON.stringify(obj1) === JSON.stringify(obj2); // true
  • The above expression will return boolean true since the string representation of objects is equal and we can infer that objects are also equal.

  • Using JSON.stringify() method is a fast approach.

See the above code live in JSBin.

Caveat: We can only use this method for simple JSON representative objects and other complex objects with many nested methods and DOM nodes may not work as expected.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter