Number.isNaN()
is a Number
method that checks if a value is NaN
(Not A Number).
NaN
in JavaScript is also a type ofNumber
.
The Number.isNaN()
method returns true
if the value is of the type Number
and is equal to NaN
. Otherwise, the method returns false
.
Number.isNaN()
is different from the globalisNaN()
function. The globalisNaN()
function first converts the value to aNumber
, then tests it.
Number.isNaN()
does not convert passed values to a Number
and does not return true
for any value that is not of the type Number
.
Number.isNaN(value);
value
: the value to be tested.Number.isNaN()
returns true
if the passed value is NaN
and is of the type Number
. Otherwise, it returns false
.
In the example below, we pass some values to the Number.isNaN()
function and log the results to the console.
console.log("Number.isNaN('NaN') ="+ Number.isNaN('NaN')) //falseconsole.log("Number.isNaN(NaN) ="+ Number.isNaN(NaN)) //trueconsole.log("Number.isNaN(0 / 0) ="+ Number.isNaN(0 / 0)) //trueconsole.log("Number.isNaN(222) ="+ Number.isNaN(222)) //falseconsole.log("Number.isNaN(-Math.pow(2, 4)) ="+ Number.isNaN(-Math.pow(2, 4))) //falseconsole.log("Number.isNaN(5-2) ="+ Number.isNaN(5-2)) //falseconsole.log("Number.isNaN(0) ="+ Number.isNaN(0)) //falseconsole.log("Number.isNaN('123') ="+ Number.isNaN('123')) //falseconsole.log("Number.isNaN('Hello') ="+ Number.isNaN('Hello')) //falseconsole.log("Number.isNaN('2005/12/12') ="+ Number.isNaN('2005/12/12')) //falseconsole.log("Number.isNaN('') ="+ Number.isNaN('')) //falseconsole.log("Number.isNaN(false) ="+ Number.isNaN(false)) //falseconsole.log("Number.isNaN(true) ="+ Number.isNaN(true)) //falseconsole.log("Number.isNaN(undefined) ="+ Number.isNaN(undefined)) //falseconsole.log("Number.isNaN({}) ="+ Number.isNaN({})) //falseconsole.log("Number.isNaN([]) ="+ Number.isNaN([])) //falseconsole.log("Number.isNaN(sqrt(-1)) ="+ Number.isNaN(Math.sqrt(-1))) // true
In the example above, the only cases that return true
(other than the explicit NaN
) are instances where we try to divide by zero or obtain the square root of a negative number. Both these instances return a Number
of type NaN
.