Object Is Distinguishes Minus Zero And Nan
Object.is compares with SameValue semantics: NaN equals itself and minus zero differs from zero, where === collapses both distinctions.
Code
// === 把 -0 与 0 视为相等、NaN 与 NaN 视为不等;Object.is 用 SameValue 语义逐位比较
console.log('-0 === 0:', -0 === 0);
console.log('NaN === NaN:', NaN === NaN);
console.log('Object.is(-0, 0):', Object.is(-0, 0));
console.log('Object.is(NaN, NaN):', Object.is(NaN, NaN));
console.log('Object.is(1, 1):', Object.is(1, 1));
// -0 会在取整运算里悄悄出现:Object.is 能把它和 0 区分开
const rounded = Math.round(-0.4);
console.log('Math.round(-0.4):', rounded);
console.log('Object.is(rounded, -0):', Object.is(rounded, -0));
// Set/Map 按 SameValueZero 去重:NaN 算同一个值,-0 与 0 也算同一个键
const s = new Set([NaN, NaN]);
console.log('set size with duplicate NaN:', s.size);Output
Captured from a sandboxed run of this snippet in the build pipeline.
-0 === 0: true
NaN === NaN: false
Object.is(-0, 0): false
Object.is(NaN, NaN): true
Object.is(1, 1): true
Math.round(-0.4): -0
Object.is(rounded, -0): true
set size with duplicate NaN: 1What the code does
Top-level bindings rounded hold the demo state — nothing sits inside a function scope.
Applying it
The run emits 8 labeled sections — -0 === 0:, NaN === NaN:, Object.is(-0, 0):, Object.is(NaN, NaN):, Object.is(1, 1):, Math.round(-0.4):, Object.is(rounded, -0):, set size with duplicate NaN: — one per step.
Statements that matter
const s = new Set([NaN, NaN]);
Interactive Tools for This Topic
JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `rounded`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.