How to deep equal in Javascript?

In JavaScript, comparing two objects can be tricky when we need to ensure that these objects are identical not only in terms of structure, but also in terms of the actual data they contain. This article dives deep into the topic of equality to demonstrate a fluent and accurate way to handle this issue.

The problem with JSON.stringify

Some of the people trying to use stringify, but comparing two objects using JSON.stringify will produce an incorrect result if the objects have the same keys and values, but in a different order. This method transforms an object into a string where key-value pairs follow the order in which they were defined. Therefore, if the order of fields in two otherwise identical objects is different, it will produce an incorrect result.

JSON.stringify({ a: 100, b: true }) == JSON.stringify({ b: true, a: 100 }); 
// Returns false

An overkill solution: deep-equal dependency

It's possible to solve this using the deep-equal package available from npm. However, this package comes with a heap of 50 external dependencies, which is excessive for such a small task, and may compromise the stability and efficiency of the project.

Write your own function to compare data

It looks like a good idea at first glance, but time-consuming, and reinventing the wheel is not a good solution in my opinion. Engineering should reuse the existing solution to save time and do more user-facing tasks.

Use lodash's isEqual function

Consider a more elegant solution using lodash's _.isEqual function. It performs a deep comparison between two values to determine if they are equivalent. Here's how to use it:

const _ = require('lodash');

const person1 = {
  "name": "Kam",
  "lastName": "De",
  "age": 25
}

const person2 = {
  "name": "Kam",
  "lastName": "De",
  "age": 25
}

_.isEqual(person1, person2); // returns true

Using Node's assert function

A built-in Node.js package assert provides a method called deepStrictEqual that tests for deep equality. Like the lodash solution above, it's quite clean and doesn't require an additional library if you're already working in a Node.js environment.

const assert = require('assert');

const person1 = {
  "name": "Kam",
  "lastName": "De",
  "age": 25
}

const person2 = {
  "name": "Kam",
  "lastName": "De",
  "age": 25
}

console.log(assert.deepStrictEqual(person1, person2)); // Returns true

Summary

Deep equality in JavaScript may seem tricky at first, but with knowledge and the right tools, the problem can be solved efficiently. Both Lodash's _.isEqual method and Node's built-in assert.deepStrictEqual function provides a clean and reliable way to compare objects for deep equality. But please remember - sometimes using popular libraries like deep-equal, or solutions like stringify, can be a completely bad idea for your project and maintenance.

Happy comparing!