NaN and -0 in Sets
You'll learn how JavaScript Sets handle two tricky numeric values: NaN and negative zero.
The Special Cases
Sets determine uniqueness using an algorithm called "SameValueZero," which handles two edge cases differently than normal JavaScript equality:
NaN is Treated as Equal to Itself
In normal JavaScript, NaN === NaN is false (NaN is never equal to itself). However, Sets treat all NaN values as identical. You can only add one NaN to a Set:
const mySet = new Set();
mySet.add(NaN);
mySet.add(NaN);
mySet.add(NaN);
console.log(mySet.size); // 1 (only one NaN stored)
console.log(mySet.has(NaN)); // true
This prevents Sets from filling up with multiple "different" NaN values, which would be useless.
Negative Zero Equals Positive Zero
JavaScript distinguishes between +0 and -0 in some contexts, but Sets treat them as the same value:
const mySet = new Set();
mySet.add(0);
mySet.add(-0);
console.log(mySet.size); // 1 (both zeros treated as identical)
// Whichever was added first is kept
for (const value of mySet) {
console.log(Object.is(value, -0)); // depends on insertion order
}
Why This Matters
Think of Sets like a guest list where duplicates aren't allowed. For NaN, it would be chaos if each "not-a-number" was considered unique—you'd have countless duplicate entries. For zeros, treating +0 and -0 differently would create confusion in most practical scenarios.
Key Takeaway: Sets use "SameValueZero" equality: NaN equals NaN (unlike ===), and -0 equals +0, ensuring predictable deduplication behavior.