Photo by Rattap on Unsplash
NaN then poisons all other math functions, leading to all other math operations resulting in NaN.
Photo by Chris Barbalis on Unsplash
Division by zero
What is NaN anyway?
NaN is a property of the global object. The initial value of NaN is Not-A-Number ? the same as the value of Number.NaN. ? MDN Docs
Photo by Andrew Buchanan on Unsplash
Checking for NaN is harder than it seems
Unfortunately, there are two problems with trying to check for NaN:
- The typeof NaN is ?number?
Check out this code example:
So how do we check whether we have a NaN value that will poison math?
Photo by Wolfgang Rottmann on Unsplash
Check for NaN with self-equality
?NaN, and only NaN, will compare unequal to itself.? ? MDN Docs
Because NaN is not equal to itself, NaN != NaN will always return true.
Of course, such a NaN test in your code is not always readable, so it is a good idea to use a comment or to create a wrapper function:
It doesn?t make a difference if you use != or !== to check for NaN.
Photo by Erik Mclean on Unsplash
Check for NaN with Object.is()
?The Object.is() method determines whether two values are the same value.? ? MDN Docs
Unlike the strict and loose equality operators, the ES6 helper method Object.is() does not consider NaN to be equal to itself:
So, if you swap out === for Object.is(), you never have to worry about checking for NaN any special way. Problem solved!
ES6 (ECMAScript 2015) added a helper function called Object.is() that is slightly different from the === operator.
Photo by Tony Hand on Unsplash
A word about Number.isNan()
Note that Number.isNan() is different from the global isNan() function, which is an older implementation whose actual purpose is to check whether a value cannot be coerced to a number.
Here?s the difference, for completeness:
- isNaN() will return true if the value is currently NaN, or if it is going to be NaN after it is coerced to a number. In other words, if it receives a value that can be coerced to a number, isNaN() will return false.
- Number.isNaN() will return true only if the value is currently NaN.
So, if you are supporting old browsers (especially Internet Explorer) that don?t support Number.isNan(), then it is best to check for self-equality.
Photo by Nick Hillier on Unsplash
- The Mozilla Developer Network Docs include details about NaN:
The global NaN property is a value representing Not-A-Number. NaN is a property of the global object. The initial value?
- Kuba Michalski explains null, undefined, and NaN in CodeBurst:
Understanding null, undefined and NaN.