Why You Shouldn’t Use JSON.stringify to Compare Objects in JavaScript
Don’t forget about the order of your keys

Equality in JavaScript is one of the most confusing aspects that’ll make you scratch your head. Unlike other languages where you would think that the equality operator ==
or ===
would behave as they should, but to your surprise, they don’t.
Because objects are reference types, so you can’t use your normal equality operators, i.e. ==
or ===
.
How do you check objects for equality then? There are a couple of approaches you can take (check at the end of the article), but this article is focused on why you shouldn’t use JSON.stringify
.
Why Not JSON.stringify
?
JSON.stringify
seems to be the most obvious and easiest choice for comparison as no external dependency is required.
But wait! It’s not as simple as it seems, as the name suggests this method converts objects to strings first and comparison takes place afterward.
JavaScript doesn’t guarantee the order of the keys. Example:

So, if the objects to be compared have properties entered in the same order, comparison will work just fine, but in the latter case, where the order has changed, the equality fails.
Conclusion
Although it works without installing libraries or packages from npm, JSON.stringify
certainly isn’t the best option to compare objects.