JavaScript Collections: SameValueZero Equality
Quick answer
Map key and Set membership comparisons use SameValueZero semantics: NaN matches NaN, signed zeros match, and other values follow strict equality behavior.
How it works
Compare three useful relations: === does not match NaN to itself; Object.is does, but distinguishes positive and negative zero; SameValueZero treats both NaN and the two zeros as matching. No conversion of string to number occurs. Objects are matched by identity.
const s = new Set([NaN, NaN, -0, 0, "0"]); console.log(s.size, s.has(NaN), s.has(-0));Expected output in Node.js:
3 true trueNaN duplicates and signed zeros collapse; the string is distinct.
console.log(NaN === NaN, Object.is(NaN, NaN), Object.is(-0, 0));Expected output in Node.js:
false true falseStrict equality and SameValue differ at NaN and signed zero.
Common mistakes
Do not use loose equality to simulate collection membership; it introduces coercions that Map and Set do not perform.
Practice
Explain why a Set of NaN, NaN, -0, 0 and "0" has three members; compare the result with Object.is.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Collections: SameValueZero Equality — Knowledge Check
Apply the taught concept and predict the output.
Does SameValueZero coerce the string "1" to the number 1?
Which equality relation distinguishes signed zero?
How many Set entries result from two distinct empty objects?
What is the exact console output in JavaScript Collections: SameValueZero Equality example 1?
const s = new Set([NaN, NaN, -0, 0, "0"]); console.log(s.size, s.has(NaN), s.has(-0));What is the exact console output in JavaScript Collections: SameValueZero Equality example 2?
console.log(NaN === NaN, Object.is(NaN, NaN), Object.is(-0, 0));