How to check if two objects are equal in JavaScript?

March 18, 2021 - 1 min read

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.

NOTE: For this method to work both the object's keys should be of the same order.

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 😃.