Object comparison Complexity in JavaScript using comparison operator or JSON.stringlify()?

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.


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");
   console.log("using == operator result ==> false");
if (JSON.stringify(object1) == JSON.stringify(object2))
   console.log("using JSON.stringify() operator result ==> true");
   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.


The output is as follows −

PS C:\Users\Amit\JavaScript-code> node demo224.js
using == operator result ==> false
using JSON.stringify() operator result ==> true