Let’s say the following are our objects −
var object1 = { firstName: "David" }; var object2 = { firstName: "David" };
You will not get the correct result using comparison operator (== or ===). Use JSON.stringify() for this.
Example
Following is the code implementing both the ways and showing the correct result −
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() operator result ==> true"); else console.log("using JSON.stringify() operator result ==> false");
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo224.js.
Output
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo224.js using == operator result ==> false using JSON.stringify() operator result ==> true