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
Selected Reading
Object comparison Complexity in JavaScript using comparison operator or JSON.stringlify()?
In JavaScript, comparing objects using comparison operators (== or ===) checks reference equality, not content equality. For content comparison, JSON.stringify() can be used with limitations.
The Problem with Comparison Operators
When comparing objects with == or ===, JavaScript checks if both variables reference the same object in memory, not if their contents are identical:
var object1 = { firstName: "David" };
var object2 = { firstName: "David" };
var object3 = object1;
console.log("object1 == object2:", object1 == object2); // false - different objects
console.log("object1 === object2:", object1 === object2); // false - different objects
console.log("object1 === object3:", object1 === object3); // true - same reference
object1 == object2: false object1 === object2: false object1 === object3: true
Using JSON.stringify() for Content Comparison
JSON.stringify() converts objects to strings, allowing content comparison:
var object1 = { firstName: "David" };
var object2 = { firstName: "David" };
if (object1 == object2) {
console.log("using == operator result ==> true");
} else {
console.log("using == operator result ==> false");
}
if (JSON.stringify(object1) == JSON.stringify(object2)) {
console.log("using JSON.stringify() result ==> true");
} else {
console.log("using JSON.stringify() result ==> false");
}
using == operator result ==> false using JSON.stringify() result ==> true
Limitations of JSON.stringify()
While JSON.stringify() works for simple cases, it has important limitations:
// Property order matters
var obj1 = { a: 1, b: 2 };
var obj2 = { b: 2, a: 1 };
console.log("Different order:", JSON.stringify(obj1) === JSON.stringify(obj2));
// Functions and undefined are ignored
var obj3 = { name: "John", func: function() {} };
var obj4 = { name: "John" };
console.log("With function:", JSON.stringify(obj3) === JSON.stringify(obj4));
Different order: false With function: true
Comparison Methods
| Method | Checks | Limitation |
|---|---|---|
| == / === | Reference equality | Cannot compare content |
| JSON.stringify() | String representation | Property order, functions ignored |
Conclusion
Use JSON.stringify() for simple object content comparison, but be aware of its limitations with property order and non-JSON values. For complex comparisons, consider using a deep equality library.
Advertisements
