Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the importance of _isEqual() method in JavaScript?
The _.isEqual() method from Underscore.js and Lodash libraries provides deep equality comparison for JavaScript objects. Unlike native JavaScript comparison operators, it performs value-based comparison rather than reference-based comparison.
Why _.isEqual() is Important
JavaScript's native equality operators (== and ===) only check if two objects are the same reference in memory, not if they have the same content. The _.isEqual() method solves this by performing deep comparison of object properties, regardless of property order.
Syntax
_.isEqual(object1, object2);
It accepts two values as parameters and returns true if they are equivalent, false otherwise.
Example: Basic Object Comparison
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script>
var obj1 = {name: "Sikha", designation: "Content developer"};
var obj2 = {name: "Sikha", designation: "Content developer"};
document.write(_.isEqual(obj1, obj2));
</script>
</body>
</html>
true
Comparison with JSON.stringify()
The JSON.stringify() method is sensitive to property order, while _.isEqual() ignores it. This makes _.isEqual() more reliable for object comparison.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script>
var obj1 = {name: "Sikha", designation: "Content developer"};
var obj2 = {designation: "Content developer", name: "Sikha"};
document.write("_.isEqual(): " + _.isEqual(obj1, obj2));
document.write("<br>");
document.write("JSON.stringify(): " + (JSON.stringify(obj1) === JSON.stringify(obj2)));
</script>
</body>
</html>
_.isEqual(): true JSON.stringify(): false
Comparison Table
| Method | Property Order Sensitive | Deep Comparison | Handles Complex Objects |
|---|---|---|---|
=== |
N/A | No | No |
JSON.stringify() |
Yes | Limited | Limited |
_.isEqual() |
No | Yes | Yes |
Key Benefits
- Order-independent: Compares objects regardless of property order
- Deep comparison: Recursively compares nested objects and arrays
- Type-aware: Handles different data types appropriately
- Reliable: More consistent than JSON.stringify() for object comparison
Conclusion
The _.isEqual() method is essential for accurate object comparison in JavaScript. It provides deep, order-independent comparison that native operators and JSON.stringify() cannot match reliably.
