Set Value Uniqueness
You'll learn how Sets keep only one copy of each value by using a special equality check called SameValueZero.
How Sets Determine Uniqueness
When you add a value to a Set, JavaScript checks whether that value already exists using an algorithm called SameValueZero. This is almost identical to strict equality (===), but with one key difference: it treats NaN as equal to itself.
Here's what that means in practice:
const mySet = new Set();
mySet.add(5);
mySet.add(5);
mySet.add(5);
console.log(mySet.size); // 1 - only one 5 stored
mySet.add("hello");
mySet.add("hello");
console.log(mySet.size); // 2 - only one "hello" stored
The NaN Special Case
Unlike strict equality where NaN !== NaN, Sets treat all NaN values as the same:
const numbers = new Set();
numbers.add(NaN);
numbers.add(NaN);
numbers.add(0 / 0); // also NaN
console.log(numbers.size); // 1 - only one NaN
Objects Are Compared by Reference
Sets use reference equality for objects, so two objects with identical properties are still different:
const items = new Set();
items.add({ name: "Alice" });
items.add({ name: "Alice" });
console.log(items.size); // 2 - different object references
const person = { name: "Bob" };
items.add(person);
items.add(person);
console.log(items.size); // 3 - same reference, only added once
Think of a Set like a bouncer at a club checking IDs: they recognize the exact same person (reference), not just people who look alike (same values).
Key Takeaway: Sets use SameValueZero equality to ensure uniqueness—identical primitives are stored once, NaN equals itself, and objects must be the same reference to be considered duplicates.