Comparing identical Objects in Javascript

danimal92

Daniel Zaltsman

Posted on February 22, 2020

Comparing identical Objects in Javascript

Javascript has a funny way of using comparison. If you were to use the strict equality operator like primitives like strings and numbers, it checks the value. However, between plain objects, arrays, and dates, it will compare the reference. This will check to see if the objects both refer to the same location in memory.

Image from Gyazo

As you can see here, the apple and cherry comparison comes to false even with the same value, but not the same reference. Between the raspberry and the apple, they are the same as they have both the same value and reference. Again, the comparison is false between raspberry and cherry as the reference is not the same.

How do we know if two objects are identical?

Here is a basic approach to checking between two objects:

Image from Gyazo

For more extreme edge cases, you should rely on a well tested library like Underscore and Lodash. They both have a method named _.isEqual that handles deep comparisons.

💖 💪 🙅 🚩
danimal92
Daniel Zaltsman

Posted on February 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related