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:
- Abstract Equality (
==): Performs type coercion, converting operands to a common type before comparing, which frequently causes unexpected results. - Strict Equality (
===): Compares values without type coercion, but fails in two critical edge cases:- It treats
NaNas not equal to itself (NaN === NaNevaluates tofalse). - It treats positive zero and negative zero as identical
(
+0 === -0evaluates totrue).
- It treats
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)); // true2. 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)); // falseBehavior with Primitives and Objects
For all other values, Object.is() behaves identically to
the strict equality operator (===):
- Primitives: Values like strings, booleans, non-zero
numbers,
undefined, andnullevaluate totrueonly if they have the same type and the same value. - Objects: Objects, arrays, and functions are
compared by reference, not by structure. Two distinct objects evaluate
to
falseeven if they have identical properties.
// 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
- State Management in Frameworks: React uses
Object.isin algorithms likeReact.memo,useMemo, and within theuseStatehook to determine if state has changed and if a component needs to re-render. - Mathematical Calculations: In graphics, physics
engines, or division-heavy logic where the sign of zero affects the
outcome (such as
1 / +0returningInfinityversus1 / -0returning-Infinity). - Safe Value Tracking: When tracking changes across
datasets that may include special numeric values like
NaNwithout requiring additional guard clauses.