Understanding NaN in JavaScript: Representation and Comparison
JavaScript’s NaN represents undefined numeric results, appears when operations like Math.sqrt(-1) occur, has multiple binary forms, and is distinguished as Quiet or Signaling; because NaN !== NaN, comparisons rely on special checks such as isnan, with implementations varying across environments like V8 and Apple’s C library.
This article explores the concept of NaN (Not a Number) in JavaScript, addressing two key questions: the result of typeof 1/undefined and the output of [1,2,NaN].indexOf(NaN). It explains that NaN appears in scenarios that violate real number calculation rules, such as Math.sqrt(-1), but not in cases like 1/0.
The article delves into how NaN is represented in floating-point numbers, explaining the three-part structure: sign bit, exponent bit, and precision bit. It demonstrates how to create NaN by manipulating memory bits and shows that NaN can be represented in multiple ways (e.g., 0x7f81111, 0x7fcccccc).
The article distinguishes between two types of NaN: Quiet NaN (which can be used in operations without throwing errors) and Signaling NaN (which throws exceptions when used). It explains why NaN !== NaN by default, noting that the probability of two NaNs having identical binary representations is extremely low.
The implementation details are explored, showing how different systems handle NaN comparison. In Apple's C library, isnan is implemented as x !== x, while V8 handles NaN at compile time by replacing NaN constants with their binary representations and at runtime by checking for NaN before comparison.
The article concludes with practical insights about NaN behavior in JavaScript and provides references for further reading on related topics.
Youzan Coder
Official Youzan tech channel, delivering technical insights and occasional daily updates from the Youzan tech team.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.