Sub topic 9
Object.is and the SameValue Family
This chapter assumes you already know how === works and how == converts its operands, which earlier chapters covered. You should also be comfortable running snippets in Node.js or a browser console.
JavaScript has more equality algorithms than it has equality operators. The language specification defines four ways to decide whether two values are "the same." You can call two of them directly through operators, and you can call one through a function. The fourth is used internally by built-in methods and collections. Knowing which algorithm a built-in uses explains results that otherwise look inconsistent.
The Four Equality Algorithms
| Algorithm | How you reach it | Converts types? | `NaN` equals `NaN`? | `0` equals `-0`? |
|---|---|---|---|---|
| IsLooselyEqual | `==`, `!=` | Yes | No | Yes |
| IsStrictlyEqual | `===`, `!==`, `indexOf`, `switch` | No | No | Yes |
| SameValueZero | `includes`, `Map`, `Set` | No | Yes | Yes |
| SameValue | `Object.is`, property redefinition | No | Yes | No |
The last three never convert types. Values of different types are never equal under them, and two objects are equal only when they are the same reference. They disagree on exactly two special numbers: NaN and -0.
- IsStrictlyEqual follows IEEE 754 floating-point rules, which say
NaNis not equal to anything, including itself, and that0and-0compare equal. - SameValue asks whether two values are indistinguishable.
NaNis alwaysNaN, so it matches itself. You can tell-0apart from0(for example,1 / -0is-Infinity), so they do not match. - SameValueZero is SameValue with one exception: it treats
0and-0as equal.
const pairs = [
[NaN, NaN],
[0, -0],
[1, '1'],
[null, undefined],
];
const sameValueZero = (x, y) => x === y || (x !== x && y !== y);
for (const [x, y] of pairs) {
console.log(
String(x), String(y),
'==', x == y,
'===', x === y,
'SVZ', sameValueZero(x, y),
'Object.is', Object.is(x, y)
);
}
// NaN NaN == false === false SVZ true Object.is true
// 0 0 == true === true SVZ true Object.is false
// 1 1 == true === false SVZ false Object.is false
// null undefined == true === false SVZ false Object.is falseThe first column prints 0 0 for the 0 and -0 pair because String(-0) is '0'. That is another way -0 stays hidden.
How Object.is Works Internally
Object.is(x, y) implements SameValue. Engines provide it natively, but writing it out with === shows the two places where it differs:
function objectIs(x, y) {
if (x === y) {
// Equal under ===, but 0 and -0 must still be separated.
// 1 / 0 is Infinity and 1 / -0 is -Infinity.
return x !== 0 || 1 / x === 1 / y;
}
// Not equal under ===. The only value not equal to itself is NaN.
return x !== x && y !== y;
}
console.log(objectIs(NaN, NaN)); // true
console.log(objectIs(0, -0)); // false
console.log(objectIs(-0, -0)); // true
console.log(objectIs('a', 'a')); // true
console.log(objectIs({}, {})); // falseThe x !== x test is the old way to detect NaN. Number.isNaN(x) does the same thing and is easier to read.
Where Each Algorithm Hides in Built-ins
You rarely call Object.is yourself. Much more often, a built-in picks the algorithm for you, and you need to know which one it picked.
Array search methods
indexOf and lastIndexOf use IsStrictlyEqual, so they can never find NaN. includes was added later and uses SameValueZero, so it can.
const values = [1, NaN, -0];
console.log(values.indexOf(NaN)); // -1
console.log(values.includes(NaN)); // true
console.log(values.indexOf(0)); // 2 (-0 === 0)
console.log(values.includes(0)); // true
console.log(values.findIndex(Number.isNaN)); // 1
console.log(values.findIndex((v) => Object.is(v, -0))); // 2If you need to find the position of NaN, or to tell -0 apart from 0, use findIndex with a predicate.
switch statements
switch compares each case with IsStrictlyEqual, so a case NaN: can never match.
function describe(n) {
switch (n) {
case NaN:
return 'matched NaN';
case 0:
return 'zero';
default:
return 'other';
}
}
console.log(describe(NaN)); // 'other'
console.log(describe(-0)); // 'zero'Map and Set keys
Map and Set use SameValueZero for keys. NaN works as a key, and -0 is stored as +0.
const seen = new Set([NaN, NaN, 0, -0]);
console.log(seen.size); // 2: one NaN, one zero
const labels = new Map();
labels.set(-0, 'zero');
console.log(labels.get(0)); // 'zero'
const [key] = labels.keys();
console.log(Object.is(key, -0)); // false: the key was normalized to +0The spec chose SameValueZero here because programs often produce -0 by accident, such as -1 * 0 or Math.round(-0.2). A cache keyed on numbers would split into two entries for what users think of as one value.
Property redefinition
When you try to redefine a property that is non-writable and non-configurable, the engine uses SameValue to decide whether the new value really changes anything. Redefining with the same value is allowed. Changing -0 to 0 counts as a change.
const frozenZero = {};
Object.defineProperty(frozenZero, 'z', {
value: -0,
writable: false,
configurable: false,
});
Object.defineProperty(frozenZero, 'z', { value: -0 }); // allowed: SameValue says equal
try {
Object.defineProperty(frozenZero, 'z', { value: 0 });
} catch (e) {
console.log(e instanceof TypeError); // true
}Choosing an Algorithm
Some practical cases:
- Change detection. If you skip work when "the value hasn't changed,"
===reports thatNaNhas always changed, which can cause endless re-renders or recomputation. React compares state and hook dependencies withObject.isfor this reason. - Numeric code that cares about sign. In some geometry and physics code,
-0records which direction a value approached zero from. OnlyObject.iskeeps that information. - Membership tests. Prefer
includesoverindexOf(...) !== -1. It reads better and handlesNaN.
Common Mistakes
- Assuming
Object.isis just a stricter===everywhere. It is looser forNaNand stricter for zero. - Using
indexOfto search arrays that may containNaN, for example data that came throughparseFloat. - Expecting a
Mapto keep0and-0as separate keys. - Writing
x === NaNto detectNaN. That check is alwaysfalse, so useNumber.isNaN(x).
Exercise
Predict each result: [NaN].indexOf(NaN), [NaN].includes(NaN), new Set([0, -0, NaN, NaN]).size, Object.is(-0, 0), Object.is(NaN, 0 / 0).
Show answer
-1, true, 2, false, true. indexOf uses strict equality, so it never finds NaN. includes and Set use SameValueZero, so NaN matches itself and 0 and -0 collapse into one entry. Object.is separates the two zeros, and 0 / 0 evaluates to NaN, which SameValue treats as equal to NaN.
Exercise
Write a function sameValueZero(x, y) that uses only === and !== and matches the behavior of Array.prototype.includes for a single element.
Show answer
function sameValueZero(x, y) { return x === y || (x !== x && y !== y); } The first test covers every ordinary case and already treats 0 and -0 as equal. The second test returns true only when both values are NaN, because NaN is the only value that is not strictly equal to itself.
Exercise
A memoization helper caches results in a Map keyed by a numeric argument. A caller passes -0 and later reads the cache with 0. Do the two calls share an entry? What would change if the helper stored keys in an array and searched it with indexOf?
Show answer
Yes. Map uses SameValueZero and normalizes -0 to +0, so both calls hit the same entry. With an array and indexOf, the two zeros would still match because -0 === 0 is true. NaN arguments, however, would never be found, so every NaN call would miss the cache and add a duplicate entry.