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, 2019 · 2 min read
Image for post
Image for post
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:

Image for post
Image for post
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.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store