Skip to main content

NaN

What is NaN

NaN is a special numeric value in JavaScript meaning:

"Not a Number" - meaning exactly that: not a number.

But NaN itself has the type "number".

javascript
typeof NaN; // "number"

In other words, NaN is simply an invalid numeric value. It appears when the result of a mathematical operation cannot be expressed as a number.


When NaN appears

Some typical cases:

javascript
Number('hello'); // NaN - could not convert the string to a number parseInt('abc'); // NaN 0 / 0; // NaN - mathematically undefined Math.sqrt(-1); // NaN - cannot take the square root of a negative number 'abc' * 3; // NaN - a string cannot be multiplied undefined + 5; // NaN

How to check a value for NaN

isNaN(value) - the old function

javascript
isNaN(NaN); // true isNaN('hello'); // true (!) isNaN('123'); // false

The problem: isNaN first converts the value to a number, and then checks whether it is NaN. So the string 'hello' → NaN, and the result is true.


Number.isNaN(value) - the modern and correct way

javascript
Number.isNaN(NaN); // true Number.isNaN('hello'); // false Number.isNaN(undefined); // false Number.isNaN(5); // false Number.isNaN(0 / 0); // true

Number.isNaN() does not convert the argument to a number, and works only if the value is actually equal to NaN.


Why NaN === NaN returns false

This may seem strange, but it's a quirk of IEEE 754 - the standard JavaScript uses to implement floating-point numbers.

Under the IEEE-754 standard, NaN is not equal even to itself.

Because NaN is not a specific value but a marker of a computation error, and there can be many such "error" states (different bit combinations → different kinds of NaN).

So:

javascript
NaN === NaN; // false NaN == NaN; // false

How to correctly check whether a value is NaN

The correct way:

javascript
Number.isNaN(value);

or if you want it short:

javascript
const isReallyNaN = x => x !== x; isReallyNaN(NaN); // true, because only NaN !== NaN

The trick: NaN is the only value in JS that is not equal to itself.


Summary

CheckResultComment
typeof NaN"number"Type is number, even though it means "not a number"
NaN === NaNfalsePer IEEE-754
isNaN('text')trueConverts to a number first (a poor choice)
Number.isNaN('text')falseThe modern, correct choice
Number.isNaN(NaN)trueChecks without type conversion

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.