Not a Number (NaN) Cheatsheet
A Cheatsheet about Not a Number (NaN) in JavaScript.
Properties & Functions
JavaScript has the global NaN property and two functions to check for NaN values.
NaN
Represents Not-A-Number
Is the result of expressions that should produce a number but failed (e.g. parsing the string
"hello"as a number)Is of type
number
(typeof NaN === 'number')Fails equality comparison
(NaN === NaNisfalse)
isNaN() 👎
Checks if the value is
NaNafter parsing it to a numberReturns
trueif the value isNaNReturns
trueif the value can't be parsed to a number (like"hello")Returns
falseif the value can be parsed to a number (like"42")Returns
falseif the value is a valid number (like42)
Number.isNaN() 👍
Checks if the value is
NaN(without parsing the value to a number)Returns
trueif the value isNaNReturns
falsefor all other values
Producing NaN
There are several ways to produce a NaN value.
Convert to number
Converting a value to a number that can't be converted to a number results in NaN.
parseInt("hello")Not a real number
Doing a math operation where the result is not a real number results in NaN.
Math.sqrt(-1)Operation with NaN
Doing a math operation with NaN results in NaN.
42 + NaNIndeterminate form
Operations that are in indeterminate forms produce NaN.
undefined + undefinedOperation with string
Doing an operation with a string that can't be parsed to a number produces NaN, except for addition operations (which join the values).
"hello" * 2Overview
The table below shows for each value the result of the operators and functions.
const x = | typeof x | parseInt(x) | Number(x) | isNaN(x) | Number.isNaN(x) | x === x |
|---|---|---|---|---|---|---|
NaN | number | NaN | NaN | true | true | false |
undefined | undefined | NaN | NaN | true | false | true |
null | object | NaN | 0 | false | false | true |
"" | string | NaN | 0 | false | false | true |
"hello" | string | NaN | NaN | true | false | true |
"42" | string | 42 | 42 | false | false | true |
"42hello" | string | 42 | NaN | true | false | true |
"hello42" | string | NaN | NaN | true | false | true |
42 | number | 42 | 42 | false | false | true |
The isNaN() function returns true whenever Number() returns NaN. The parseInt() function works different than Number() but this doesn't affect the result of isNaN().