Quirks of NaN
NaN literally means Not-A-Number right? Seems obvious, I mean it’s in the name after all. A quick check of its data type will confirm this:
What the fuck?
Rather ironic for the thing called “Not-A-Number” to actually be a number data type. So why is this? In JavaScript, as well as being part of the global object, it is also a property of Number
.
For this reason NaN is actually considered a number. No worries if you’re a bit confused trying to wrap your head around this. NaN is a type of number so think of it as a number with an undefined value, one that is returned from an illogical math statement to indicate a problem with the calculation.
Okay, so NaN is actually a number. It’s value is similar to undefined
so what happens if we check for NaN and add edge cases if it’s returned. Let’s give it a try.
Seriously bro? NaN
is not equal to NaN
. Make it make sense.
NaN (Not-a-Number) is the only JavaScript value not equal to itself when compared with any of the comparison operators.
Since NaN cannot be compared to itself how can a value be checked to see if it is NaN? There are two methods, the global isNaN()
and Number.isNaN()
.
Both methods will return a boolean determining if the value passed is NaN. On the surface they look the same but they function differently.
Why does "100x"
return true
for isNaN()
and false
for Number.isNaN()
? When the data type of the value given to the global isNaN()
method is not a number it will first try to convert it to a number and then check if it is NaN.
The string "100x"
cannot be converted to a valid number and subsequently is declared NaN and isNaN()
returns true
. The Number.isNaN()
method does not convert the input value. Instead it returns true only if the data type is both a number and NaN. Because "100x"
is a string and not a number the return value is false
.
Due to the inherent conversion of inputs to numbers with isNaN()
it is recommended to use Number.isNan()
in most cases.
NaN can be tricky to understand. It stands for Not-A-Number but actually is a type of number. It is the only value in JavaScript that cannot be compared to itself. Its presence can only be checked with two methods that function differently and can return undesired results if misunderstood. The good news is knowing these concepts lays the groundwork for understanding what NaN is, how it works, and how to handle it.
Last updated