The Number isNaN() method
By Flavio Copes
Learn how the JavaScript Number.isNaN() method works, returning true only for NaN or 0/0 and false for every other value you pass to it.
Number.isNaN() tells you if the value you pass is exactly NaN. It returns true only for NaN itself, or for an expression that produces NaN, like dividing 0 by 0. For every other value, it returns false:
Number.isNaN(NaN) //true
Number.isNaN(0 / 0) //true
Number.isNaN(1) //false
Number.isNaN('Flavio') //false
Number.isNaN(true) //false
Number.isNaN({}) //false
Number.isNaN([1, 2, 3]) //false
Why does this method exist?
NaN is a special value. It’s the only value in JavaScript that is not equal to itself:
NaN === NaN //false
So you can’t check for NaN with a comparison. The comparison always fails, even when the value really is NaN. Number.isNaN() exists to do that check reliably.
When would you use it?
NaN shows up when a number operation fails. The typical case is parsing user input:
const price = parseFloat('not a price')
price //NaN
Number.isNaN(price) //true
Any math involving NaN also produces NaN, so one bad value can silently spread through your calculations. Checking with Number.isNaN() right after parsing lets you catch the problem early.
Watch out for the global isNaN()
Be careful: there’s also a global isNaN() function, and it behaves differently. The global version converts its argument to a number first, then checks the result:
isNaN('Flavio') //true
Number.isNaN('Flavio') //false
The string 'Flavio' is not NaN. It’s a string. But converting it to a number produces NaN, so the global isNaN() says true.
That coercion causes surprises. isNaN(undefined) returns true too, even though undefined is not NaN either.
My advice is to use Number.isNaN(). It answers one precise question: is this value NaN? No conversion, no surprises.
One last detail worth knowing: NaN stands for “Not a Number”, but its type is number:
typeof NaN //'number'
Strange, but that’s how the language defines it. It’s a numeric value that represents a failed numeric result.
Related posts about js: