JavaScript: Deep Comparison of Objects with a Recursive Call

Bahay Gulle Bilgi
Analytics Vidhya
Published in
3 min readMay 24, 2020

In this post, I will explain the solution of the Deep Comparison exercise in the Eloquent Javascript book (3rd edition, chapter 4):

Write a function deepEqual that takes two values and returns true only if they are the same value or are objects with the same properties, where the values of the properties are equal when compared with a recursive call to deepEqual.

Let’s break the exercise into smaller parts and explain it step by step:

Step 1:

The function deepEqual takes in two arguments; value 1(v1) and value 2(v2). In the first step, we will use the strict equality operator (===) to check if the types and values of the two arguments are the same.

Step 2:

Next, we need to check if the types of both arguments are object and are not null. If both arguments are object, we will move forward and compare their properties with a deep comparison.

Step 3:

After we are certain that both arguments are object, we will check if they have the same properties and values. Comparing the number of objects’ keys is a good start to eliminate the ones with differences in the length of their properties. We will use Object.keys() method to return the list of the objects’ properties and set up the variables v1keys & v2keys.

Step 4:

In the last step, we will iterate through all the properties of the v1with a for in loop to make sure that every property in the v1also exists in the v2. If the objects we are comparing have the same properties, checking their values will be the last thing to do. This is where we need to use the deepEqual function recursively (calling itself) by passing the values of each property into it to check if they are equal. If there is a property with different values of each object, it will exit the loop and return false.

If none of the above conditions are met after the loop checks every property and value, it will return true at the end of the function. Here is the complete function with all the explained steps:

I hope this helps, thanks for reading!

--

--