In JavaScript, comparing two objects can be tricky. Even if two objects have the same properties and values, they’re not equal unless they reference the same memory. Let’s see how object equality works and how to simplify deep comparisons using the _.isEqual method from Underscore.js.
Strict Equality Doesn’t Work for Objects
const a = { name: 'Alice' };
const b = { name: 'Alice' };
console.log(a === b); // false
Why? Because a and b are different objects in memory, even if they look identical.
Reference Equality
const c = a;
console.log(a === c); // true — same reference
Comparing Object Contents Manually
You can write a basic deep equality check like this:
function isEqual(obj1, obj2) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
for (let key of keys1) {
if (obj1[key] !== obj2[key]) return false;
}
return true;
}
console.log(isEqual(a, b)); // true
This works for simple objects, but not for nested ones.
Using Underscore.js: _.isEqual
Underscore makes this much easier:
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
<script>
const a = { name: 'Alice', info: { age: 30 } };
const b = { name: 'Alice', info: { age: 30 } };
console.log(_.isEqual(a, b)); // true
</script>
_.isEqual does a deep recursive comparison of all properties, including nested objects and arrays.
When to Use _.isEqual
- Comparing configuration objects
- Checking if props or state changed in React
- Validating form data against saved data
Limitations
- Comparing functions or class instances may not behave as expected
- Deep comparison can be slower for large or complex objects
Conclusion
JavaScript’s strict equality (===) only compares object references, not their contents. For comparing actual values, write a manual deep comparison for simple cases, or use _.isEqual from Underscore.js for a reliable and readable solution. It saves time, avoids bugs, and handles nested structures gracefully.
Post a Comment