If you have you ever written a program that parses the value of a number input by using
parseFloat, then you have run into the infamous
What Is NaN?
parseInt('') parseFloat('Some String')
Both of the above function calls will return
Some other ways that
NaN is returned are as follows.
- Math that cannot return a real number
- Any math that involves a string (besides
+since that will concatenate strings)
"string" * 7
- Any operation that has
NaN * 3
How To Check For NaN
By far the most complicated thing about
NaN is how you check for
NaN. If you want to check to see if a value is
NaN your first thought would be to do the following.
NaN == NaN // or NaN === NaN
Unfortunately, this does not work since these equality checks will return
false. This is because
NaN will always return false when compared to any other value, even another
This is where the biggest confusion with
NaN comes about. Instead of using a normal equality check you need to use the function
isNaN to check if a variable is
This function will properly return
false depending on if
NaN or not.
Type Coercion Shenanigans
If this wasn't already confusing enough, there is a second form of the
isNaN function called
Number.isNaN. These functions work nearly identically to each other, but they handle type coercion differently.
isNaN function will return true if the variable passed to it is
NaN or if the variable will be
NaN after it is coerced into a number. This means that
isNaN(NaN) will both return true.
Number.isNaN on the other hand does not do any coercion and will only return true if the value passed to it is
NaN. This means that
Number.isNaN("string") will return false, while
Number.isNaN(NaN) will return true.
NaN is fairly confusing since it is never equal to anything. This makes for some tricky bugs to track down if you are not aware of how
NaN is handled. If you ever need to check for
NaN make sure to use the
isNaN function instead.