Number Edge Cases (NaN, Infinity, Floating Point)
JavaScript's single numeric type is 64-bit floating point, which produces predictable rounding error and two special non-finite values.
Number.isNaN(x) / Number.isFinite(x)
Purpose
JavaScript has one numeric type, a 64-bit IEEE 754 floating-point number, used for both integers and decimals. That single representation produces a few well-known, predictable surprises.
Examples
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(10 / 0); // Infinity
console.log(-10 / 0); // -Infinity
console.log(0 / 0); // NaN
console.log(typeof NaN); // "number"
Behavior notes
- Most decimal fractions have no exact binary floating-point representation, so arithmetic on them accumulates tiny rounding error. This isn’t specific to JavaScript — it’s true of floating point in nearly every language.
Infinityand-Infinityresult from dividing by zero (or overflowing the representable range) rather than throwing an error.NaN(“Not a Number”) results from an invalid numeric operation (0 / 0,Number("abc")).NaNis the only JavaScript value that is never equal to itself —NaN === NaNisfalse.
Common mistakes
- Comparing floating-point results for exact equality (
0.1 + 0.2 === 0.3isfalse). Compare within a small tolerance instead, or work in integers (cents instead of dollars) when exactness matters. - Checking for
NaNwith=== NaNor== NaN— both always evaluate tofalse. UseNumber.isNaN(x). - Confusing the global
isNaN()withNumber.isNaN()— the global version coerces its argument first (isNaN("abc")istrue), whileNumber.isNaN("abc")isfalsebecause a string is neverNaNitself, only an invalid conversion result.
Runtime notes
The Number type and its edge cases are defined by ECMAScript and behave identically across
engines.