Emmanuel Akinfulubi

JavaScriptValidation

Object.is vs === vs deep equality in JavaScript

Advanced · 4 min read

"Are these two values the same?" comes up everywhere: has a form changed since it was saved, should a list re-render, does a test result match what you expected. JavaScript gives you more than one answer to that question, and they disagree on a few values.

In this tutorial you will compare values at three levels: ===, Object.is, and a deepEqual function you write yourself that looks inside objects and arrays. You should know objects, arrays and ===. Recursion, a function calling itself, is explained when we need it.

Values and references

For primitives like numbers and strings, === compares the values themselves. For objects and arrays, it compares references: it asks "is this the very same object?", not "do these look alike?".

JavaScript

console.log('bus' === 'bus');      // true
console.log({ a: 1 } === { a: 1 }); // false

const o = { a: 1 };
const same = o;
console.log(o === same);            // true

The two { a: 1 } objects have the same contents, but they are two separate objects, so === says no. same points at the very same object as o, so that one is true.

Two odd numbers

JavaScript numbers include NaN ("Not a Number", the result of a failed calculation) and -0, a zero with a minus sign. You can get -0 from ordinary math:

JavaScript

console.log(Object.is(Math.round(-0.4), -0)); // true
console.log(1 / 0);                            // Infinity
console.log(1 / -0);                           // -Infinity

Rounding -0.4 gives -0. String(-0) turns it into the text "0", so the sign is easy to miss. Dividing by it shows the sign is real.

Here is the exercise. Try it on your own first if you like, or read on and we will build it step by step.

10 Are two values the same?

hard

Compare two values. Cover the three levels: ===, Object.is, and a deep comparison that looks inside objects and arrays.

Stuck? Three hints, smallest first
  1. 1. === gets two things wrong: NaN === NaN is false, and 0 === -0 is true.
  2. 2. Object.is fixes exactly those two cases and nothing else.
  3. 3. Neither looks inside objects, so {a:1} === {a:1} is false. That needs recursion.

Step 1: what === gets wrong

=== is right almost all the time. It gets exactly two cases wrong:

JavaScript

console.log(NaN === NaN); // false
console.log(0 === -0);    // true

NaN isn't equal to itself, and 0 and -0 count as equal even though they behave differently.

Step 2: Object.is

Object.is works like === except in those two cases:

Step 2

const sameValue = (a, b) => Object.is(a, b);

console.log(sameValue(1, 1));           // true
console.log(sameValue(NaN, NaN));       // true
console.log(sameValue(0, -0));          // false
console.log(sameValue(null, undefined)); // false
console.log(sameValue({}, {}));         // false

Like ===, it still compares objects by reference, so two empty objects are different.

Step 3: start deepEqual with the easy cases

To compare contents, we need our own function. Start with the cases that need no looking inside:

JavaScript

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

console.log(deepEqual(NaN, NaN));  // true
console.log(deepEqual(1, '1'));    // false
console.log(deepEqual(null, {}));  // false
console.log(deepEqual({}, {}));    // look inside

If the two are the same value, we are done. If either isn't an object, they can't be equal by contents. null needs its own line, because typeof null is 'object'. The last line is a placeholder for what comes next.

Step 4: compare keys, and go deeper

Now compare contents. Object.keys(obj) lists an object's own keys (for an array, its indexes). If the counts differ, the objects differ. Otherwise, every key in a must exist in b with an equal value.

"Equal value" might itself be an object, so we call deepEqual again on each pair. A function that calls itself like this is called recursive. It stops when it reaches simple values.

Step 4

function deepEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (typeof a !== 'object' || typeof b !== 'object') return false;
  if (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((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
}

console.log(deepEqual({ a: 1, b: 2 }, { b: 2, a: 1 }));         // true
console.log(deepEqual({ a: 1 }, { a: 1, b: 2 }));                // false
console.log(deepEqual({ a: { b: [1, 2] } }, { a: { b: [1, 2] } })); // true
console.log(deepEqual([1, 2], [2, 1]));                          // false
console.log(deepEqual({ a: NaN }, { a: NaN }));                  // true
console.log(deepEqual([1], { 0: 1 }));                           // true, but wrong

Key order doesn't matter, nesting works, and NaN inside an object is handled because the first line uses Object.is. A version built on === would call { a: NaN } unequal to itself.

The last line is a bug. The array [1] and the object { 0: 1 } have the same keys and values, but one is an array and one isn't.

Step 5: arrays must match arrays

Add one line before the key comparison:

JavaScript

if (Array.isArray(a) !== Array.isArray(b)) return false;

If one is an array and the other isn't, they aren't equal. With that line in place, deepEqual([1], { 0: 1 }) returns false. This is the version in the full solution.

This deepEqual still has limits. It only looks at own keys, so it doesn't understand dates, maps, sets or objects that refer to themselves:

JavaScript

function deepEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (typeof a !== 'object' || typeof b !== 'object') return false;
  if (a === null || b === null) return false;
  if (Array.isArray(a) !== Array.isArray(b)) return false;
  const aKeys = Object.keys(a);
  const bKeys = Object.keys(b);
  if (aKeys.length !== bKeys.length) return false;
  return aKeys.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
}

console.log(deepEqual(new Date(2026, 0, 1), new Date(2030, 0, 1))); // true, but wrong

A date keeps its time hidden, with no own keys, so two different dates look equal. A full deep-equal has to handle each of those types on purpose.

The full solution

The panel has sameValue and the finished deepEqual, and prints the cases === gets wrong. Press Run to see them and all the checks.

The answer

// Level 2: === with its two oddities corrected. This is what Object.is does.
const sameValue = (a, b) => Object.is(a, b);

// Level 3: recurse into arrays and plain objects.
function deepEqual(a, b) {
  if (Object.is(a, b)) return true;                       // handles NaN and -0 correctly

  if (typeof a !== 'object' || typeof b !== 'object') return false;
  if (a === null || b === null) return false;
  if (Array.isArray(a) !== Array.isArray(b)) return false;

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

  return aKeys.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
}

console.log('--- the two cases === gets wrong ---');
console.log('NaN === NaN     :', NaN === NaN, '   Object.is:', Object.is(NaN, NaN));
console.log('0 === -0        :', 0 === -0, '   Object.is:', Object.is(0, -0));
console.log('--- neither looks inside ---');
console.log('{a:1} === {a:1} :', { a: 1 } === { a: 1 }, '   deepEqual:', deepEqual({ a: 1 }, { a: 1 }));
console.log('--- and why 1/-0 matters at all ---');
console.log('1 / 0  =', 1 / 0);
console.log('1 / -0 =', 1 / -0, '<- so the sign of zero is not decoration');

Output


      
22 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 22 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

22 checks

test('two equal numbers', sameValue(1, 1), true);
test('two equal strings', sameValue('a', 'a'), true);
test('NaN equals NaN under Object.is', sameValue(NaN, NaN), true);
test('but not under ===', NaN === NaN, false);
test('0 and -0 differ under Object.is', sameValue(0, -0), false);
test('but not under ===', 0 === -0, true);
test('and the difference is real: 1/-0 is -Infinity', 1 / -0, -Infinity);
test('null equals null', sameValue(null, null), true);
test('null does not equal undefined', sameValue(null, undefined), false);
test('two separate objects are not the same value', sameValue({}, {}), false);
test('but they are deeply equal', deepEqual({}, {}), true);
test('matching contents are deeply equal', deepEqual({ a: 1, b: 'x' }, { a: 1, b: 'x' }), true);
test('key order does not matter', deepEqual({ a: 1, b: 2 }, { b: 2, a: 1 }), true);
test('a different value is not equal', deepEqual({ a: 1 }, { a: 2 }), false);
test('an extra key is not equal', deepEqual({ a: 1 }, { a: 1, b: 2 }), false);
test('nesting is handled', deepEqual({ a: { b: [1, 2] } }, { a: { b: [1, 2] } }), true);
test('and a nested difference is caught', deepEqual({ a: { b: [1, 2] } }, { a: { b: [1, 3] } }), false);
test('arrays compare by contents', deepEqual([1, 2, 3], [1, 2, 3]), true);
test('order matters in an array', deepEqual([1, 2], [2, 1]), false);
test('an array is not the same as an object with number keys', deepEqual([1], { 0: 1 }), false);
test('NaN inside an object is handled', deepEqual({ a: NaN }, { a: NaN }), true);
test('the same reference is equal to itself', (() => { const o = { a: 1 }; return sameValue(o, o); })(), true);

Object.is differs from === in exactly two places: NaN now equals itself, and 0 no longer equals -0. That second one looks pedantic until you divide by it — 1 / -0 is -Infinity, so the sign survives and can change a result.

The deep comparison is where the real decisions are. Using Object.is as its base case is what makes { a: NaN } equal itself, which a ===-based version gets wrong. The Array.isArray(a) !== Array.isArray(b) line stops [1] matching { 0: 1 }, which have the same keys and values. And this version compares own enumerable keys only, so it does not handle dates, Maps, Sets or cycles — a real deep-equal has to decide about each of those, which is why the same() helper used by these tests takes the cheap route of comparing JSON strings.

Common mistakes

  • Comparing objects with ===. It checks whether they are the same object, not whether they have the same contents.
  • Building deepEqual on ===. Then { a: NaN } isn't equal to itself. Use Object.is for the base case.
  • Forgetting the array check. Without it, [1] equals { 0: 1 }.

Try it yourself

  1. Add a date rule to deepEqual: if both values are dates, compare getTime().
  2. Write hasChanged(saved, current) for a form, using deepEqual.
  3. Compare JSON.stringify(a) === JSON.stringify(b) with deepEqual on { a: 1, b: 2 } and { b: 2, a: 1 }, and explain the difference.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.