Home
← All questions

Deep equality check in JavaScript

MediumPremiumJavaScript

JavaScript interview practice: Implement a deep equality comparison for objects and arrays.

Problem

Comparing state snapshots, memoizing selectors and writing test assertions all need a deep equality check in JavaScript, because === only tells you whether two objects are the same reference.

Write a function deepEqual(a, b) that returns true when a and b are structurally equal by value, and false otherwise.

Requirements

  • Primitives are equal when they are strictly equal (1 vs "1" is false).
  • NaN is considered equal to NaN.
  • null and undefined are only equal to themselves; comparing null with an object returns false.
  • Two plain objects are equal when they have the same set of own enumerable keys and every corresponding value is deeply equal. Key order does not matter.
  • Two arrays are equal when they have the same length and equal elements at every index.
  • Nesting can be arbitrarily deep and can mix objects and arrays.

Example

deepEqual(3, 3);                                   // true
deepEqual(NaN, NaN);                               // true
deepEqual({ x: 1, y: 2 }, { y: 2, x: 1 });         // true
deepEqual({ user: { tags: ["a", "b"] } },
          { user: { tags: ["a", "b"] } });         // true
deepEqual({ x: 1 }, { x: 1, y: undefined });       // false
deepEqual(["a", "b"], ["b", "a"]);                 // false
deepEqual({ x: null }, { x: {} });                 // false

Follow-ups

  • How would you compare Date, RegExp, Map and Set values correctly?
  • What happens with circular references, and how would you support them?
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium