liveBook · Manning

Nan

As explained in JavaScript in Depth

A special JavaScript numeric value representing an undefined or unrepresentable floating-point result.

NaN is JavaScript’s result for a numeric conversion or operation that cannot produce a number. A comparator returning NaN behaves like +0, so sorting ISO date-time strings can silently return the original arrival order. section 4.4.1

Trace the conversion chain before trusting a numeric expression:

  • Numeric subtraction converts operands to numbers; nonnumeric ISO date-time strings therefore produce NaN. section 4.4.1
  • Array-to-number conversion first creates a string: [1] becomes '1', while [1,2] becomes '1,2' and then NaN. section 4.4.4
  • Repeated implicit conversions add constant-factor cost and can turn a measured sort or render-path operation into a production performance problem. section 4.4.4

A sort that does nothing

Calling timestamps.sort((a, b) => a - b) works for numeric timestamps and numeric strings, but produces NaN for ISO date-time strings. Because every comparison appears equal, the array remains in arrival order. section 4.4.1

console.log(Number([1]));  // 1
console.log(Number([1,2]));  // NaN

Run the contrasting array conversions to observe why a one-element array becomes 1 while a two-element array becomes NaN. section 4.4.4

How JavaScript in Depth covers it

How deep it goes
Explains comparator behavior, conversion chains, and performance consequences through worked examples, without detailing numeric internals.
Examples
Uses timestamp sorting, ISO date-time strings, array conversion, and payment arithmetic to expose NaN-producing paths.
What you can do after
Diagnose NaN-producing coercions and prevent them with explicit type checks or a type-safe variant such as TypeScript.
How it connects
Connects NaN to type coercion, array conversion, sorting, type checking, performance, and TypeScript.

Also explained in

Compare how 10 books explain nan →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.