JavaScript Object.is: Purpose and How It Works

The Object.is() method in JavaScript determines whether two values are the same value. Introduced in ECMAScript 2015 (ES6), its primary purpose is to provide a reliable, predictable equality algorithm—known as the SameValue algorithm—that resolves the edge-case inconsistencies present in the standard strict equality operator (===).

Why Object.is Was Introduced

In JavaScript, comparison operators have historical quirks:

  1. Abstract Equality (==): Performs type coercion, converting operands to a common type before comparing, which frequently causes unexpected results.
  2. Strict Equality (===): Compares values without type coercion, but fails in two critical edge cases:
    • It treats NaN as not equal to itself (NaN === NaN evaluates to false).
    • It treats positive zero and negative zero as identical (+0 === -0 evaluates to true).

Object.is() resolves these edge cases by implementing strict value identity.

Key Differences: Object.is vs. Strict Equality (===)

There are only two differences in behavior between Object.is() and the === operator:

1. Handling of NaN

Under strict equality, NaN is the only value in JavaScript that is not equal to itself. Object.is() treats NaN as equal to NaN.

// Strict Equality
console.log(NaN === NaN); // false

// Object.is
console.log(Object.is(NaN, NaN)); // true

2. Handling of +0 and -0

Strict equality treats positive and negative zero as equal. Object.is() distinguishes between them based on their sign bit.

// Strict Equality
console.log(+0 === -0); // true

// Object.is
console.log(Object.is(+0, -0)); // false

Behavior with Primitives and Objects

For all other values, Object.is() behaves identically to the strict equality operator (===):

// Primitive comparison
console.log(Object.is('hello', 'hello')); // true
console.log(Object.is(true, false));       // false

// Reference comparison
console.log(Object.is({}, {}));           // false (different references)

const obj = { a: 1 };
console.log(Object.is(obj, obj));         // true (same reference)

Common Use Cases

  1. State Management in Frameworks: React uses Object.is in algorithms like React.memo, useMemo, and within the useState hook to determine if state has changed and if a component needs to re-render.
  2. Mathematical Calculations: In graphics, physics engines, or division-heavy logic where the sign of zero affects the outcome (such as 1 / +0 returning Infinity versus 1 / -0 returning -Infinity).
  3. Safe Value Tracking: When tracking changes across datasets that may include special numeric values like NaN without requiring additional guard clauses.