Equality (===)
This compares the references of the objects. If the references point to the same object, it returns “true”, otherwise “false”.
Syntax:
object_1 === object_2
Example: To demonstrate the comparison of the JavaScript Object Reference.
// Example of different reference
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
console.log(obj1 === obj2);
// Example of same reference
const obj3 = { a: 1, b: 2 };
const obj4 = obj3;
console.log(obj3 === obj4);
Output:
false
true
How to Compare Objects in JavaScript?
In JavaScript, comparing objects is not as simple as comparing numbers or strings. Objects are compared based on their memory references, so even if two objects have the same properties and values, they are considered distinct if they are stored in different memory locations.
Below are the various approaches to compare objects in JavaScript:
Table of Content
- Equality (===)
- JSON.stringify()
- Lodash Library
- Object.entries()
- Object.keys()