OneBite.Dev - Coding blog in a bite size

compare two objects in javascript

Code snippet for how to how to compare two objects in javascript with sample and detail explanation

In this article, we’re going to explore how to compare two objects in JavaScript. It’s an important and common task in web development and understanding it will help you solve complex problems more efficiently.

Code Snippet: Comparison of Two Objects in JavaScript

let object1 = {name: 'John', age: 25};
let object2 = {name: 'John', age: 25};

let compareObjects = (obj1, obj2) => {
    return JSON.stringify(obj1) === JSON.stringify(obj2);
};

console.log(compareObjects(object1, object2));  // This will return true

Code Explanation for Comparison of Two Objects in JavaScript

Firstly, we define two objects, object1 and object2, which we want to compare.

let object1 = {name: 'John', age: 25};
let object2 = {name: 'John', age: 25};

Then, the function compareObjects is created. This function takes in two objects (herein referred to as obj1 and obj2) as parameters and performs the actual comparison.

let compareObjects = (obj1, obj2) => {
    return JSON.stringify(obj1) === JSON.stringify(obj2);
};

This function uses the JSON.stringify() method to convert the objects into a string format, making the comparison possible. The JSON.stringify() method converts a JavaScript object or value to a JSON string. When we compare these stringified versions using the strict equality operator ===, it checks whether both the objects have the same keys, the same corresponding values and they appear in the same order in both objects.

Next, we run the function with object1 and object2 as parameters. The result check is logged on the console.

console.log(compareObjects(object1, object2));  // This will return true

In this case, object1 and object2 are identical, having the same keys and values in the same order, hence the return value is true.

javascript