Why not use JSON.stringify in JavaScript?

|
| By Webner

Why JSON.stringify Shouldn’t Be Used To Compare Objects In JavaScript?

In javascript, equality operator == or === can be used to compare numerics and strings. But when we will compare objects using these operators, then it will not work as expected because objects use references. So, equality operators will compare references instead of values of objects.

How do you check objects for equality then? There are a couple of approaches you can use, but this article is focused on why you shouldn’t use JSON.stringify.

JSON.stringify is the easiest choice to compare two objects. But, it is not as simple as it seems. The name of the method defines that it converts objects to strings first, then it will compare the converted strings.

However, if we compare the same objects with different key order, then it will not work as given in the example below:

Example

JSON.stringify({name:”demo”, status:”Active”}) === JSON.stringify({name:”demo”, status:”Active”}) // it will return true
JSON.stringify({name:”demo”, status:”Active”}) === JSON.stringify({status:”Active”,name:”demo”}) // it will return false

So, if the objects to be compared have properties entered in the same order, the comparison will work just fine. But in the latter case, where the order has changed, the equality fails.

Leave a Reply

Your email address will not be published. Required fields are marked *