`isNaN` vs `Number.isNaN` (hint: use the latter)
Chalk this up to JavaScript is just weird. The isNaN
function returns some surprising values:
> isNaN(NaN)
true
> isNaN({})
true
> isNaN('word')
true
> isNaN(true)
false
> isNaN([])
false
> isNaN(1)
false
What's going on here? Per MDN, the value is first coerced to a number (like with Number(value)
) and then if the result is NaN
it returns true
.
Number.isNaN
is a little bit more literal:
> Number.isNaN(NaN)
true
> Number.isNaN({})
false
> Number.isNaN('word')
false
> Number.isNaN(true)
false
> Number.isNaN([])
false
> Number.isNaN(1)
false
So, if you really want to know if a value is NaN
use Number.isNaN
I learned about this via Lydia Hallie's Javascript Questions
Tweet