Better Programming

Advice for programmers.

Follow publication

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

Don’t forget about the order of your keys

Zain Zafar
Better Programming
Published in
2 min readOct 14, 2019
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:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Zain Zafar
Zain Zafar

Written by Zain Zafar

Frontend Enthusiast, JavaScript Hacker with affinity to Design & Blogger

Responses (5)