Understanding NaN & Number.isNaN better!

Understanding NaN & Number.isNaN better!

isNaN(v)

isNaN is a function that takes up a value and tells if it is NaN or not? Pretty sweet?

But what is NaN? Does that mean "it's not a number"? This mental model will create confusions when you think, for example, strings, obviously string is different from a number. So isNaN for strings should return true?

Check this!

let value = "hi";
isNaN(value); // true

How?

Above statement returned true, but how? Is it really because we gave it a string and since string is not a number so return true? If you thought so, then check this

let value2 = "42";
isNaN(value2) // false

How come it's false even though we passed a string 42.

Let's check the spec!

image.png

Seeing the spec we now know that isNaN function first tries to convert the provided value to a number using Number(). Since value used did not have a valid numerical representation, Number() returned NaN hence it returns true, which is not the case for value2

Number("hi") // NaN
Number("42") // 42

hence the output!

So, a better mental model is if we say that NaN denotes an Invalid Number.

This mental model also clears the confusion you have

typeof NaN; // 'number'

So, NaN is a number (it's just invalid)

Number.isNaN (spec)

Apart from the global isNaN , es6 introduced Number.isNaN. This does not convert the given value before checking for NaN rather, simply returns false if the provided value is not of type number.

hence,

Number.isNaN("hi") // false
Number.isNaN("42") // false

Both false because the conversion to number does not happen in this case at all as opposed to its global variant.

Hope it helped!