# How to compare two objects using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jun 18, 2020, updated Aug 12, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javacript-compare-objects

> A quick guide to learn how to compare two objects in JavaScript to check if they contain they same key-value pairs.

To compare two JavaScript objects to check if they have the same key-value pairs:

1. Use `JSON.stringify()` to convert objects into strings and then compare the JSON strings.
2. Use Lodash, a 3rd-party library, `isEqual()` to perform a deep comparison between the objects.

Unlike JavaScript [arrays comparison](https://attacomsian.com/blog/javascript-compare-arrays), you can not use `===` and `==` operators to perform objects comparison. This is because objects are reference types in JavaScript and only point to the memory location where they are stored.

## `JSON.stringify()` Method

The fastest and simplest way to compare two objects is to convert them to strings by using the `JSON.stringify()` method and then use the comparison operator to check if both strings are equal:

```javascript
const obj1 = { burger: '?', pizza: '?' };
const obj2 = { burger: '?', pizza: '?' };

// compare objects
if (JSON.stringify(obj1) === JSON.stringify(obj2)) {
    console.log('Objects are equal!');
} else {
    console.log('Objects are not equal.');
}

// Objects are equal!
```

This method works only when the key-value pairs have the **same order**. If the key-value pairs are arranged differently in the two objects but are the same, this method will return `false`:

```javascript
const obj1 = { burger: '?', pizza: '?' };
const obj2 = { pizza: '?', burger: '?' };

// compare objects
if (JSON.stringify(obj1) === JSON.stringify(obj2)) {
    console.log('Objects are equal!');
} else {
    console.log('Objects are not equal.');
}

// Objects are not equal.
```

For objects having arbitrary key-value pairs order, you should consider using Lodash's `isEqual()` method.

## Lodash `isEqual()` Method

The `isEqual()` method from [Lodash](https://lodash.com/docs/4.17.15#isEqual) performs a deep comparison between two objects to determine if they are equivalent. The key-value pairs order doesn't matter for this method. It will return `true` as long as key-value pairs exist and are the same. You can even use this method to compare arrays, strings, dates, booleans, array buffers, etc.

Here is an example:

```javascript
const _ = require('lodash');

const obj1 = { burger: '?', pizza: '?' };
const obj2 = { pizza: '?', burger: '?' };

if (_.isEqual(obj1, obj2)) {
    console.log('Objects are equal!');
} else {
    console.log('Objects are not equal.');
}

// Objects are equal!
```

To learn more about JavaScript objects, prototypes, and classes, read [this article](https://attacomsian.com/blog/objects-prototypes-classes-javascript).
