Key Equality and Reference in Maps
You'll learn: How Maps determine if two keys are the same, including special cases like NaN and object references.
How Maps Compare Keys
When you set or get a value in a Map, JavaScript needs to decide whether the key you're using matches an existing key. Maps use an internal algorithm called SameValueZero for this comparison.
Here's what makes it special:
Primitives Work as Expected
For strings, numbers, and booleans, keys match if their values are identical:
const map = new Map();
map.set(5, 'five');
map.set('hello', 'world');
console.log(map.get(5)); // 'five'
console.log(map.get('hello')); // 'world'
The NaN Special Case
Unlike === (strict equality), Maps treat NaN as equal to itself:
const map = new Map();
map.set(NaN, 'not a number');
console.log(map.get(NaN)); // 'not a number' ✓
console.log(NaN === NaN); // false (with ===)
This solves a common JavaScript quirk where NaN === NaN is false.
Object References, Not Content
Maps compare object identity (memory reference), not their contents:
const map = new Map();
const key1 = { id: 1 };
const key2 = { id: 1 };
map.set(key1, 'first');
map.set(key2, 'second');
console.log(map.size); // 2 (different keys!)
console.log(map.get(key1)); // 'first'
console.log(map.get(key2)); // 'second'
Even though key1 and key2 look identical, they're different objects in memory, so they're treated as separate keys.
Key Takeaway: Maps use SameValueZero equality—primitives match by value (with NaN === NaN), but objects match only if they're the exact same reference in memory.