Why You Shouldn’t Use JSON.stringify to Compare Objects in JavaScript

Don’t forget about the order of your keys

Zain Zafar
Oct 14 · 2 min read
Photo by Adeolu Eletu on Unsplash

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:

View the code: https://gist.github.com/zainzafar90/919fd3088a912860847cdc2d33159a24

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.


Alternatives for Comparison

The JavaScript community has some other methods for object comparison:


Better Programming

Advice for programmers.

Zain Zafar

Written by

Frontend Enthusiast, JavaScript Hacker with affinity to Design & Blogger

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade