To compare two objects in JavaScript, you can use the ===
operator, which compares the object references rather than their contents.
This means that two objects with identical content will be considered different if they are not the same object reference.
For example:
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
const obj3 = obj1;
console.log(obj1 === obj2); // false
console.log(obj1 === obj3); // true
In this example, obj1
and obj2
have the same content, but they are different object references, so the comparison obj1 === obj2
returns false
. On the other hand, obj1
and obj3
are the same object reference, so the comparison obj1 === obj3
returns true
.
If you want to compare the contents of two objects, you can write a custom function that checks each property recursively.
For example:
function isEqual(obj1, obj2) {
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false;
}
for (const key in obj1) {
if (obj1.hasOwnProperty(key)) {
if (typeof obj1[key] === "object" && typeof obj2[key] === "object") {
if (!isEqual(obj1[key], obj2[key])) {
return false;
}
} else if (obj1[key] !== obj2[key]) {
return false;
}
}
}
return true;
}
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
const obj3 = { a: 1, b: { c: 3 } };
console.log(isEqual(obj1, obj2)); // true
console.log(isEqual(obj1, obj3)); // false
In this example, the isEqual
function compares each property of obj1
and obj2
recursively, and returns true
if they have the same content.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.