Comparing Values of Objects in JavaScript

Comparing Values of Objects in JavaScript

ยท

3 min read

JavaScript has only two data types. One is Primitive and other the one is the non-primitive data type. Primitive data types consist of

  • undefined
  • Boolean
  • Number
  • String
  • Symbol
  • null

And Non-Primitive data types have only one member i.e.,

  • Object

More about JavaScript data types here.

Comparing primitive data types is easy. We can easily compare two primitive data types using the equality operator. But it doesn't work for non-primitive types. Because primitive data types are compared by their values, while objects in JavaScript are compared by their reference. So, the simple equality operator will only check if the location of the two objects is the same or not. We'll understand it with a code example here.

Checking two Objects using Equality Operator

Suppose we have two objects, i.e.,

let obj1 = {key1: "a", key2: "b", key3: "c"}
let obj2 = {key1: "a", key2: "b", key3: "c"}

We can see both the objects has the same key and values. Now if we try to write a function using the equality operator

let isSame = (object1, object2) => {
  return object1 === object2;
}

If we run this function and provide obj and obj2 as parameters, the function will return false.

1

But if we define another variable that refers to an already defined object, it'll return true.

2

Here, obj1 and obj3 refer to the same memory location and hence the function returns true.

Now I think we are much clear why we shouldn't use the simple equality operator while comparing two objects.

Multiple ways can be used to compare two objects. Let's see with examples.

Code Example 1

let areEqual = (object1, object2) => {
    return 
    object1.key1 === object2.key1 && 
    object1.key2 === object2.key2 && 
    object1.key3 === object2.key3 //and so on
}

This function will return true if two objects are equal. This code works but it is way too static. We have to manually change each value for every different object having different key-value pairs.

To ease our work, we'll use the JSON.stringify method.

What is JSON.stringify

The JSON.stringify is a JavaScript method that converts a JavaScript object to a JSON string.

Syntax

JSON.stringify(value[, replacer[, space]])

The value specifies the value that has to be converted. The replacer and the space are optional arguments. You can check this article to know more about this method.

Code Example 2

let areEqual = (object1, object2) => {
  return JSON.stringify(object1) === JSON.stringify(object2) 
}

As we can see that code is just a single line and we can use this function with any two objects. We don't have to manually set up the parameters that are to be checked.

I hope you liked the article.

Did you find this article valuable?

Support Subha Chanda by becoming a sponsor. Any amount is appreciated!