Fundamentals 8 min read

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.

Youzan Coder
Youzan Coder
Youzan Coder
Understanding NaN in JavaScript: Representation and Comparison

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.

javascriptv8Floating Pointbinary representationC librarycomparison operatorsNaN
Youzan Coder
Written by

Youzan Coder

Official Youzan tech channel, delivering technical insights and occasional daily updates from the Youzan tech team.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.