Javascript Fundamentals · Interview Challenges

Deep equality

deep equal

Deep equality

You write if (user === savedUser) to check whether two objects hold the same data. It is always false, even when every field matches, because === compares objects and arrays by reference, not by shape. { a: 1 } === { a: 1 } is false: two different objects in memory.

Deep equality answers a different question: do two values hold the same contents, all the way down?

The recipe mirrors deep cloning — walk both values in lockstep:

function deepEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
    return false;
  }

  const aKeys = Object.keys(a);
  const bKeys = Object.keys(b);
  if (aKeys.length !== bKeys.length) return false;

  return aKeys.every((key) => deepEqual(a[key], b[key]));
}

The first line settles primitives and identical references using Object.is, which — unlike === — treats NaN as equal to itself. If either side is not a non-null object, it can only have matched on the first line, so the answer is false.

For two objects, compare their keys. If the key counts differ, they cannot be equal. Otherwise every key must exist on both sides with deeply equal values — which is why the comparison recurses rather than stopping at the first level.

Export deepEqual from index.js. Your job is to compare nested values structurally instead of by reference.

Challenge

Comparing two objects with === reports false even when every field matches, because it compares references rather than contents. Export a deepEqual function from index.js to compare them by shape instead.

deepEqual takes two values and returns true when they hold the same contents at every level, and false otherwise. Two distinct objects with the same nested properties must be equal, while a missing or different nested value must not be.

index.js
export function deepEqual(a, b) {
  return a === b;
}

export function render(mount) {
  const left = { a: 1, b: { c: [1, 2] } };
  const right = { a: 1, b: { c: [1, 2] } };

  const line = document.createElement('p');
  line.textContent = `Equal: ${String(deepEqual(left, right))}`;
  mount.append(line);
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.