The short story:
I would really use the typeof
operator.
From isNaN() | JavaScript MDN:
The isNaN()
function determines whether a value is Not-A-Number or not. ...
you may alternatively want to use Number.isNaN()
, as defined in ECMAScript 6, or you can use typeof
to determine if the value is Not-A-Number.
Long story:
Tried the following in a node console.
A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.
isNaN(123) // false
isNaN(true) // false
isNaN("123") // false
isNaN({}) // true
isNaN(undefined) // true
In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true.
Number.isNaN(undefined) // false
Number.isNaN({}) // false
Number.isNaN(true) // false
Number.isNaN(123) // false
Number.isNaN(NaN) // true
Number.isNaN(0/0) // true
The typeof
operator returns a string indicating the type of the unevaluated operand.
typeof(123) // number
typeof("123") // string
typeof(true) // boolean