JavaScript NaN and difference between isNaN() and Number.isNaN()

Amandeep Singh
2 min readJan 6, 2021

Introduction

NaN is a special value in JavaScript (or many programming languages) which represents that the value of a variable is Not-a-Number.

NaN is a property available in the global scope(window in case of JavaScript executing on browser). Although assigning a NaN value to variable or using NaN in a program is something that is never needed, but NaN exists to denote a operation or parsing result is not a number.

Interesting thing to note, typeof operation on a NaN results in “number” as output. so,
typeof NaN // “number”

Broadly, there are very few operations in JavaScript that will return NaN. Examples below:

  1. Parsing or typecasting to number :
const num = parseInt("xyz") //NaN
const num2 = Number("xyz") //NaN
const num3 = +"xyz" //NaN

2. Any mathematical operation on string value except for +. (+ is overloaded and “str” + Number will concat and return a string).

"xyz" / 3  //NaN
"xyz" * 4 //NaN

3. Mathematical operation where the result is not a real number or indeterminate

0 * Infinity //NaN
Math.sqrt(-10) //NaN
NaN + 7 //NaN

A special property of NaN is that NaN is never equal to any other value including itself.

NaN === NaN //false
NaN !== NaN // true

How to check for NaN?

There are 2 functions available is JavaScript to check for NaN values.

IsNaN() available is global object (window)

Number.isNaN()

The 2 functions check for NaN values but have notably different behavior and result in different outputs in corner cases.

Global isNaN()attempts to convert convert its input to number and then checks for is the result is a NaN.

isNaN(5) // false
isNaN("") //false as empty string is convertible to 0
isNaN(false) // false
isNaN(NaN) //true
isNaN("xyz") // true, as result of Number("xyz") is NaN
isNaN(null) //false as null is convertible to number 0.
isNaN(undefined) //true as Number(undefined) is NaN
isNaN("123") // false

So if we want to write a polyfill for global isNaN, we can write below

function isNaN(input) {
const convertedNumber = Number(input)
//because NaN is never equal to NaN
return convertedNumber !== convertedNumber;
}

Number.isNaN() has a slightly different algorithm than global IsNaN(). Number.isNaN() checks for type and if type is not “number” , returns false. If the type of argument is “number”, then it checks if value is NaN or not.

Number.isNaN(5) // false
Number.isNaN("") //false as typeof "" != "number"
Number.isNaN(false) // false
Number.isNaN(NaN) //true
Number.isNaN("xyz") // false, isNaN("xyz") returns true here
Number.isNaN(null) //false
Number.isNaN(undefined)// false, isNaN(undefined) returns true here
Number.isNaN("123") // false as type of "123" is "string"

Lets look at a polyfill for Number.isNaN()

function isNaN(input) {
return input!== input and typeof input === "number";
}

Thanks for reading!

--

--