How to Check for NaN in JavaScript
I came across this problem while practicing my JavaScript on Code Wars. I had some simple code performing some division, and in some cases that code would return NaN
. This was correct code, but I needed to check for it in order to have my function actually do something with it, duh.
Here is what I foolishly tried to do at first, that failed spectacularly:
let num = NaN
console.log(num === NaN ? true : false)
//false
What is NaN
NaN stands for “Not a number.” This occurs when we try to create a number and for some reason that operation fails. According to MDN, there are several operations which can result in NaN
, they are:
-
Failing to parse a number with
parseInt()
- This will fail if the object passed to
parseInt()
can’t be made into a valid number, such as a string of letters, orundefined
- This will fail if the object passed to
- A math operation that results in not a real number, ie.
Math.sqrt(-1)
- Indeterminate arguments like
0 * infinity
andundefined + undefined
- Lastly, any time NaN is an operand in an equation, the result will be
NaN
. Makes sense!
Testing for NaN
NaN
is special! This is the only thing in JavaScript that is not equal to itself. This is super interesting to me. That could come in handy. Plus, there is a special method on the Number
object prototype isNaN()
that we can use. Here are a few examples:
NaN === NaN //False, whoah!
NaN !== NaN //True!
NaN != NaN //True!
isNaN(NaN) //True!
One more thing, you can also check whether a variable would be parsed into NaN
or not. That way you don’t have to wait until your math is already broken to find out.
isNaN("1") //False
isNaN("foo") //True
Created: 2021-04-24-Sat Tags: References: