Why not use JSON.stringify in JavaScript?

Author - Webner
8.07.2020
|
0 Comments
||

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.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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