Compare Anything in JavaScript with Just A Function
Tags: javascript, algorithms, compare, webdev
Published: 2022-07-07 20:43:09




✅ In this article, we will create a function that can compare not only strings,  numbers, and booleans but also arrays and objects. The arrays and objects that this function will compare can have nested arrays, and nested objects. Also, the objects can not only have enumerable properties but also nonenumerable. If you want to see a preview, go to the last section: [Preview](#testing)


&nbsp;

> **🔖 Table of Contents**

- [Step 1: Creating the function](#step-1-creating-the-function)
- [Step 2: Checking Null](#step-2-checking-null)
- [Step 3: Checking String and Number and Boolean](#step-3-checking-string-and-number-and-boolean)
- [Important Info](#important-info)
- [Step 4: Checking Type](#step-4-checking-type)
- [Step 5: Checking total number of properties](#step-5-checking-total-number-of-properties)
- [Step 6: Checking Property Names](#step-6-checking-property-names)
- [Step 7: Checking Property Values](#step-7-checking-property-values)
- [Step 8: The Last Step](#step-8-the-last-step)
- [Full Code](#full-code)
- [Testing](#testing)




&nbsp;

### Step 1: Creating the function

&nbsp;

Let's name this function `compareAnything` and this function will accept two arguments: `first` & `second`. 

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

 ...

}
```
We can pass two values as arguments. This function will return a boolean value after comparing those values.






&nbsp;

### Step 2: Checking Null

&nbsp;


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


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

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

```




&nbsp;

### Step 3: Checking String and Number and Boolean 

&nbsp;


It's easy to compare strings, numbers, and booleans.  We just need to use a strict equality operator (===). 


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

    ...

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

}

```
If the arguments are equal, we are returning `true`. But if they are not equal, then surely they are not strings or numbers or booleans. Maybe they are objects or arrays. So, we will move forward to the next step.



&nbsp;

⚠️

###  Important Info

&nbsp;


&nbsp;

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

&nbsp;

Before going to `step 4`, let's understand why it's tough to compare two objects. 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.


![](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;

**Arrays are objects**

&nbsp;


Arrays are a special type of object. The `typeof` operator in JavaScript returns "object" for arrays.

```js
let a = [1, 2, 3]
console.log(typeof a) // object
```

So, from now we will only focus on comparing two objects. If we can make functionality to compare two objects, that functionality will also compare two arrays automatically.


&nbsp;

### Step 4: Checking Type

&nbsp;


In this step, we will make sure that the type of the argument is `object`. If any of the arguments is not an object, we will return `false`. 


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

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

```
> Note:
>
> The `typeof` operator in JavaScript returns "object" for arrays too. So, in this step, we are checking for both arrays and objects.



&nbsp;

### Step 5: Checking the total number of properties

&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 compareAnything (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: Checking Property Names

&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 compareAnything (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: Checking Property Values

&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 `compareAnything` 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 the same or not. So, actually, we need a function like this `compareAnything` 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, we can use this `compareAnything` function as a recursive function.


Now, let's use this `compareAnything` 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 compareAnything (first, second) {

    ...
    
  

 for(let key of first_keys) {



     ...

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

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



}

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




&nbsp;

### Step 8: The Last Step

&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 compareAnything (first, second) {

    ...
    
  
  for(let key of first_keys) {



     ...


   }

 return true

}

```


&nbsp;

### Full Code 

&nbsp;



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


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


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


  /* 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 compareAnything function recursively (calling itself) and passing the values of each property into it to check if they are equal. */
      if (compareAnything(first[key], second[key]) === false) return false

  }



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


}


```






&nbsp;

### Testing

&nbsp;



&nbsp;

**String**

&nbsp;

```js
const string_1 = 'rasaf'
const string_2 = 'ibrahim'
const string_3 = 'rasaf'

console.log(compareAnything(string_1, string_2)) //false
console.log(compareAnything(string_1, string_3)) // true
console.log(compareAnything(string_2, string_3)) // false
```


&nbsp;

**Number**

&nbsp;

```js
const number_1 = 100
const number_2 = 200
const number_3 = 100

console.log(compareAnything(number_1, number_2)) //false
console.log(compareAnything(number_1, number_3)) // true
console.log(compareAnything(number_2, number_3)) // false

```


&nbsp;

**Boolean**

&nbsp;


```js
const boolean_1 = true
const boolean_2 = false
const boolean_3 = true

console.log(compareAnything(boolean_1, boolean_2)) //false
console.log(compareAnything(boolean_1, boolean_3)) // true
console.log(compareAnything(boolean_2, boolean_3)) // false
```




&nbsp; 

**Array**

&nbsp;

```js
let arr_1 = [
  {
    color: 'red',
    type: 'station wagon',
    registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
    capacity: 5
  },
  {
    color: 'red',
    type: 'cabrio',
    registration: 'Sat Mar 03 2012 01:00:00 GMT+0100 (GMT+01:00)',
    capacity: 2
  }
]


let arr_2 = [
  {
    color: 'red',
    type: 'station wagon',
    registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
    capacity: 5
  },
  {
    color: 'red',
    type: 'cabrio',
    registration: 'Sat Mar 03 2012 01:00:00 GMT+0100 (GMT+01:00)',
    capacity: 2
  }
]

console.log(compareAnything(arr_1, arr_2)) //true
```


&nbsp;

**Object**

&nbsp;


```js
let obj_1 = {
  name: "Rasaf",
  additionalData: {
      favoriteHobbies: ["Playing Cricket", "Watching Movies"],
      citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
      }
  }


let obj_2 = {
  name: "Rasaf",
  additionalData: {
      favoriteHobbies: ["Playing Football", "Watching Movies"],
      citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
      }
  }


let obj_3 = {
  name: "Rasaf",
  additionalData: {
      favoriteHobbies: ["Playing Cricket", "Watching Movies"],
      citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
      }
  }

console.log(compareAnything(obj_1, obj_2)) //false
console.log(compareAnything(obj_1, obj_3)) // true
console.log(compareAnything(obj_2, obj_3)) // false
```



&nbsp;

**Object (Enumerable & Nonenumerable Properties)**

&nbsp;

```js
let obj_1 = {
  name: "Rasaf",
  additionalData: {
      favoriteHobbies: ["Playing Cricket", "Watching Movies"],
      citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
      }
  }


  let obj_2 = {
    name: "Rasaf",
    additionalData: {
        favoriteHobbies: ["Playing Cricket", "Watching Movies"],
        citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
        }
    }


let obj_3 = {
  name: "Rasaf",
  additionalData: {
      favoriteHobbies: ["Playing Football", "Watching Movies"],
      citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
      }
  }
  Object.defineProperty(obj_3, 'noneEnumble', {
    value: 123,
    enumerable: false
  });


  let obj_4 = {
    name: "Rasaf",
    additionalData: {
        favoriteHobbies: ["Playing Football", "Watching Movies"],
        citiesLivedIn: ["Rajshahi", "Rangpur", "Joypurhat"]
        }
    }
    Object.defineProperty(obj_4, 'noneEnumble', {
      value: 123,
      enumerable: false
    });




console.log(compareAnything(obj_1, obj_2)) //true
console.log(compareAnything(obj_1, obj_3)) // false
console.log(compareAnything(obj_2, obj_3)) // false
console.log(compareAnything(obj_3, obj_4)) // 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.