Deeply Compare 2 Objects with Recursive Function in JavaScript
Tags: javascript, recursion, algorithms, webdev
Published: 2022-07-05 16:36:58




In this article, we will compare two objects deeply. The objects that we will compare can not only have strings, numbers, and boolean as properties but also nested objects & arrays. Also, the property of these objects can not only be enumerable but also nonenumerable.

&nbsp;

> **Table of Contents**
- [Why it's a little bit tough to compare two objects](#why-its-a-little-bit-tough-to-compare-two-objects)
- [Let's Compare Two Objects](#lets-compare-two-objects)
  - [Step 1](#step-1)
  - [Step 2](#step-2)
  - [Step 3](#step-3)
  - [Step 4](#step-4)
  - [Step 5](#step-5)
  - [Step 6](#step-6)
  - [Step 7](#step-7)
  - [Step 8](#step-8)
- [Full Code](#full-code)
  - [Let's test](#lets-test)






&nbsp;

### Why it's a little bit tough to compare two objects

&nbsp;




In JavaScript, objects are stored by reference. That means one object is strictly equal to another only if they both point to the same object in memory.


![pass by reference vs pass by value](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3t8344gy85z2r9vq1kbh.gif)

> `This GIF is collected from panjee.com and modified afterward.`


&nbsp;



```js
const obj_1 = { score: 12 }
const obj_2 = obj_1
const obj_3 = { score: 12 }

obj_1 === obj_2; // true, same reference
obj_1 === obj_3 // false, different reference but same keys and values
```


&nbsp;

### Let's Compare Two Objects 

&nbsp;


We need to check multiple things to compare two objects. So, we will break down the comparison process into multiple steps:


&nbsp;

#### Step 1

&nbsp;

Let's first create a function (`deepComparison`) that has two parameters (`first`, `second`). 
```js
function deepComparison (first, second) {

 ...

}
```
If we pass two objects as the arguments of this function, this function will return a boolean value after comparing them. 


&nbsp;

#### Step 2

&nbsp;

Our real work is beginning from this step. In this step, we will check if the types and values of the two arguments are the same. If they are the same, we will return `true`. Otherwise, we will move forward to the next step.


```js
function deepComparison (first, second) {

    /* Using the strict equality operator (===) */
    if(first === second) return true

}

```


&nbsp;

#### Step 3

&nbsp;


In this step, we will check whether any of the arguments is `null`. If any argument is `null`, we will return `false`. But if none of them are null, we will move forward to the next step.


```js
function deepComparison (first, second) {

    ...
    
   if(first === null || second === null) return false
   
}

```



&nbsp;

#### Step 4

&nbsp;


Now, we will make sure that both arguments are objects. If any of the arguments is not an object, we will return `false`. 



```js
function deepComparison (first, second) {

    ...
    
   if(typeof first !== 'object'  || typeof second !== 'object') return false
   
}

```

&nbsp;

#### Step 5

&nbsp;


In the last step, we have made sure that both arguments are objects. In this step, we will check whether both objects have the same number of properties or not. If they don't have the same number of properties, we will return `false`. 


```js
function deepComparison (first, second) {

    ...
    
   /* Using Object.getOwnPropertyNames() method to return the list of the objects’ properties*/
 let first_keys = Object.getOwnPropertyNames(first)

 let second_keys = Object.getOwnPropertyNames(second)


  /* Using array.length() method to count the number of total property */
  if(first_keys.length !== second_keys.length) return false
   
}

```

> Could we use `Object.keys()` instead of `Object.getOwnPropertyNames()`? 
>
> No. Because `Object.keys()` can't return *Nonenumerable* 
property's name but `Object.getOwnPropertyNames()` can.




&nbsp;

#### Step 6

&nbsp;

In the last step, we made sure that both objects have the same number of properties. Now, we need to make sure that the properties' names of both objects are the same. If they are not the same, we will return `false`. But if they are the same, we will move forward to the next step.


```js
function deepComparison (first, second) {

    ...
    
  
  /* Iterating through all the properties of the first object with for..of method */
 for(let key of first_keys) {


    /* Making sure that every property in the first object also exists in the second object */ 
    if(!Object.hasOwn(second, key)) return false
    

 }


}

```

> Could we use `Object.hasOwnProperty()` instead of `Object.hasOwn()`? 
>
> No. Because `Object.hasOwnProperty()` can't check a *Nonenumerable* property's name but `Object.hasOwnProperty()` can. Also, `Object.hasOwn()` is intended as a replacement for `Object.hasOwnProperty()`, so we are using `Object.hasOwn()` here.



&nbsp;

#### Step 7

&nbsp;

In the last step, we made sure that the property names of both objects are the same. Now, we will check whether the property values of both objects are the same or not.

&nbsp;

> This step is a little bit tricky because:

&nbsp;

- The property values can not only be strings, numbers, or boolean but also nested objects.
- Just checking with strict equality operator (===) would be enough if the values were string or number or boolean but it wouldn't be enough for an object because the nested object will have its own properties. 
- Let's suppose that the nested object has another object inside it as a property! What will we do? Will we check one by one! 



&nbsp;

> Solution:

&nbsp;


- In the *step 1*, we created this `deepComparison` function, and this function not only checks the strict equality operator (===), but also it checks null or not, object or not, properties of objects are same or not. So, actually, we need a function like this `deepComparison` to check any nested object's properties.
- Fortunately, we don't need to create any new function because there is a term known as the recursive function. A recursive function is a function that calls itself during its execution. So, actually, we can use this `deepComparision` function as a recursive function.


Now, let's use this `deepComparision` function to check whether the property values of both objects are the same or not. If they are not the same, we will return `false`. 


```js
function deepComparison (first, second) {

    ...
    
  

 for(let key of first_keys) {



     ...

  
   /* Using the deepComparison function recursively and passing the values of each property into it to check if they are equal. */

  if (deepComparison(first[key], second[key]) === false) return false



}

```
> Note
>
> As the `deepComparision` is inside a loop. So, it will continue to execute itself till it finishes checking all the nested objects. 
 




&nbsp;

#### Step 8

&nbsp;


If we are in this `step 8`, that means no other step's condition matched. As we have checked almost all possible ways in which the objects are not the same and none of those conditions matched, so now we can surely say that the objects are the same. So, we will simply return `true` in this step.


```js
function deepComparison (first, second) {

    ...
    
  
  for(let key of first_keys) {



     ...


   }

 return true

}

```


&nbsp;

### Full Code 

&nbsp;



```js
function deepComparison (first, second) {


  /* Checking if the types and values of the two arguments are the same. */
  if(first === second) return true


  /* Checking if any arguments are null */
  if(first === null || second === null) return false

  /* Checking if any argument is none object */
  if(typeof first !== 'object'  || typeof second !== 'object') return false



  /* Using Object.getOwnPropertyNames() method to return the list of the objects’ properties */
  let first_keys = Object.getOwnPropertyNames(first)

  let second_keys = Object.getOwnPropertyNames(second)

 

  /* Checking if the objects' length are same*/
  if(first_keys.length !== second_keys.length) return false




  /* Iterating through all the properties of the first object with the for of method*/
  for(let key of first_keys) {


      /* Making sure that every property in the first object also exists in second object. */ 
      if(!Object.hasOwn(second, key)) return false


      /* Using the deepComparison function recursively (calling itself) and passing the values of each property into it to check if they are equal. */
      if (deepComparison(first[key], second[key]) === false) return false

  }



  /* if no case matches, returning true */ 
  return true


}


```






&nbsp;

#### Let's test

&nbsp;


```js


let obj1 = {
  a: 1,
  b: 2,
  c: { foo: 1, bar: 2},
  d: { baz: 1, bat: 2, arr: [2,3] }
}

let obj2 = {
  a: 1,
  b: 2,
  c: { foo: 1, bar: 2},
  d: { baz: 1, bat: 2, arr: [2,3] }
}


let obj3 = {
  name: "Rahim",
  additionalData: {
      instructor: true,
      favoriteHobbies: ["Playing Cricket", "Tennis", "Coding"],
      citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
      }
  }


let obj4 = {
    name: "Rahim",
    additionalData: {
        instructor: true,
        favoriteHobbies: ["Playing Cricket", "Tennis", "Coding"],
        citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
        }
    }

```


```js

console.log(deepComparison(obj1, obj2)) //true
console.log(deepComparison(obj1, obj3)) //false
console.log(deepComparison(obj2, obj3)) // false
console.log(deepComparison(obj3, obj4)) //true

```

---



That's it. 😃 Thanks for reading. 🎉 If you find any typos or errors, or if you want to add something, please write it down in the comment section.