Sub topic 4
How Keys Are Compared: SameValueZero
This chapter assumes you already know how to create a Map and a Set and call set, get, add, and has on them. It also assumes you understand the difference between primitive values and object references. The chapter covers one question: when you call map.get(x) or set.has(x), how does JavaScript decide whether x matches a stored key?
The answer is an equality algorithm called SameValueZero. It is close to ===, but it differs in two places, and those differences explain several results that surprise people.
The Four Equality Algorithms in JavaScript
JavaScript has four ways to decide whether two values are "the same." You can call three of them directly. You only reach the fourth through built-in methods.
| Algorithm | How you reach it | `NaN` vs `NaN` | `+0` vs `-0` | `'1'` vs `1` | `{}` vs `{}` |
|---|---|---|---|---|---|
| Loose equality | `==` | false | true | true | false |
| Strict equality | `===` | false | true | false | false |
| SameValue | `Object.is` | true | false | false | false |
| SameValueZero | `Map`, `Set`, `includes` | true | true | false | false |
SameValueZero takes the most useful behavior from each of the strict algorithms:
- From
Object.is, it takes the rule thatNaNequalsNaN. Without this rule, aNaNkey could never be found again. - From
===, it takes the rule that+0equals-0. Most programs never need to tell the two zeros apart. - Like both strict algorithms, it never converts types.
'1'and1stay different.
How SameValueZero Decides
The algorithm checks types first and then compares in a way that depends on the type.
Here is that process applied to a Set and a Map:
const values = new Set([NaN, NaN, 0, -0, '1', 1]);
console.log(values.size); // 4
console.log(values.has(NaN)); // true
const m = new Map();
m.set(-0, 'zero');
console.log(m.get(0)); // 'zero'
console.log(new Set([{}, {}]).size); // 2The Set ends up with four entries: NaN, 0, '1', and 1. The second NaN matches the first one, and -0 matches 0. The string and the number stay separate because SameValueZero does no type conversion. The two object literals are separate objects in memory, so they count as two entries.
Stored Zeros Are Normalized
Map and Set treat -0 as equal to +0, and they also convert -0 to +0 when they store it. Run Map.prototype.set or Set.prototype.add with -0 and the stored key comes out as +0:
const m = new Map([[-0, 'zero']]);
const [key] = m.keys();
console.log(Object.is(key, -0)); // false
console.log(Object.is(key, 0)); // true
const s = new Set([-0]);
console.log(Object.is([...s][0], 0)); // trueBecause of this conversion, iteration never gives you back a -0 you put in. Code that depends on the sign of zero, such as some vector math, needs to keep that sign somewhere other than a Map key or Set value.
Other Built-ins That Use SameValueZero
Map and Set are not the only users of SameValueZero. Array.prototype.includes and TypedArray.prototype.includes use it too. indexOf and lastIndexOf use strict equality instead. That split produces this well-known inconsistency:
const readings = [3, NaN, 7];
console.log(readings.includes(NaN)); // true (SameValueZero)
console.log(readings.indexOf(NaN)); // -1 (strict equality)
console.log(readings.findIndex(Number.isNaN)); // 1Primitive Types Beyond Numbers
Each primitive type follows the "same type, same value" rule, and a few cases are worth checking:
const keys = new Map();
keys.set(1, 'number');
keys.set(1n, 'bigint');
keys.set('1', 'string');
keys.set(true, 'boolean');
keys.set(null, 'null');
keys.set(undefined, 'undefined');
console.log(keys.size); // 6
console.log(keys.get(1n)); // 'bigint'
console.log(keys.get(BigInt(1))); // 'bigint'
const s1 = Symbol('id');
const s2 = Symbol('id');
keys.set(s1, 'first symbol');
console.log(keys.get(s2)); // undefined
console.log(keys.get(s1)); // 'first symbol'1 and 1n are different types, so they make separate keys, even though 1 == 1n is true. Two BigInts with the same value match, because BigInts are primitives. Symbols are primitives as well, but every call to Symbol() creates a unique value. Two symbols with the same description are therefore different keys. Symbol.for('id') gives back the same registered symbol each time, so it does work as a repeatable key.
The Common Error: Expecting Structural Equality
For objects, SameValueZero compares identity, not contents. People new to Map often make this mistake:
const grid = new Map();
grid.set([1, 2], 'tree');
console.log(grid.get([1, 2])); // undefined
console.log(grid.size); // 1
const today = new Map();
today.set(new Date(2026, 0, 1), 'holiday');
console.log(today.get(new Date(2026, 0, 1))); // undefinedEach [1, 2] literal creates a new array, and each new Date(...) creates a new object. The entry is still in the Map, but you can no longer look it up unless you kept a reference to the original key.
You can fix this in three ways, depending on the situation.
- Keep the original reference. If the key object already lives elsewhere in your program, such as a DOM node or a user record, look it up with that same object.
- Derive a primitive key. Turn the parts that matter into a string or number.
- Nest Maps. Index by one part and then by the next. This avoids building strings and handles parts that are objects themselves.
// Option 2: derived primitive keys
const cells = new Map();
const cellKey = (x, y) => `${x},${y}`;
cells.set(cellKey(1, 2), 'tree');
console.log(cells.get(cellKey(1, 2))); // 'tree'
const events = new Map();
const d = new Date(2026, 0, 1);
events.set(d.getTime(), 'holiday');
console.log(events.get(new Date(2026, 0, 1).getTime())); // 'holiday'
// Option 3: nested Maps
const nested = new Map();
function setCell(x, y, value) {
if (!nested.has(x)) nested.set(x, new Map());
nested.get(x).set(y, value);
}
function getCell(x, y) {
return nested.get(x)?.get(y);
}
setCell(1, 2, 'rock');
console.log(getCell(1, 2)); // 'rock'
console.log(getCell(5, 5)); // undefinedYou Cannot Customize Equality
Some languages let you override equality or hashing for a class, for example equals and hashCode in Java or __eq__ and __hash__ in Python. JavaScript has no such hook. Map and Set always use SameValueZero, and defining valueOf, toString, or Symbol.toPrimitive on an object has no effect on lookups. If you want value-based keys, convert each object to a primitive key yourself, as in the previous section, or wrap the Map in a small class that does the conversion on every call.
Exercise
What does this code print, and why? const s = new Set(['a', NaN, 0, 'a', -0, NaN, [1], [1]]); console.log(s.size);
Show answer
It prints 5. The entries are 'a', NaN, 0, and two separate arrays. The duplicate 'a' and the second NaN match existing entries. -0 matches 0 under SameValueZero. The two [1] literals are distinct objects, so both are kept.
Exercise
A colleague writes const m = new Map(); m.set({ id: 7 }, 'Ada'); and later calls m.get({ id: 7 }), which returns undefined. Explain the cause and give two fixes.
Show answer
SameValueZero compares objects by reference, and each object literal is a new object, so the lookup key is not the stored key. Fix 1: store the object in a variable and use that same reference for set and get. Fix 2: use a primitive derived from the object, such as m.set(7, 'Ada') and m.get(7), keyed by the id.
Exercise
Given const arr = [NaN]; const m = new Map([[-0, 'x']]);, what do arr.indexOf(NaN), arr.includes(NaN), m.has(0), and Object.is([...m.keys()][0], -0) return?
Show answer
-1, true, true, and false. indexOf uses strict equality, under which NaN never equals itself. includes and Map use SameValueZero. Map also normalizes a stored -0 to +0, so the stored key is not -0 according to Object.is.