Skip to content
tinytip

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 === NaN is false)

isNaN() 👎

  • Checks if the value is NaN after parsing it to a number

  • Returns true if the value is NaN

  • Returns true if the value can't be parsed to a number (like "hello")

  • Returns false if the value can be parsed to a number (like "42")

  • Returns false if the value is a valid number (like 42)

Number.isNaN() 👍

  • Checks if the value is NaN (without parsing the value to a number)

  • Returns true if the value is NaN

  • Returns false for 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 + NaN

Indeterminate form

Operations that are in indeterminate forms produce NaN.

undefined + undefined

Operation 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" * 2

Overview

The table below shows for each value the result of the operators and functions.

const x =typeof xparseInt(x)Number(x)isNaN(x)Number.isNaN(x)x === x
NaNnumberNaNNaNtruetruefalse
undefinedundefinedNaNNaNtruefalsetrue
nullobjectNaN0falsefalsetrue
""stringNaN0falsefalsetrue
"hello"stringNaNNaNtruefalsetrue
"42"string4242falsefalsetrue
"42hello"string42NaNtruefalsetrue
"hello42"stringNaNNaNtruefalsetrue
42number4242falsefalsetrue

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().