JavaScript isNaN() Function
The isNaN() function determines whether a value is an illegal number (Not-a-Number).
This function returns true if the value equates to NaN. Otherwise it returns false.
NaN values are generated when arithmetic operations result in undefined or unrepresentable values.
A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.
Syntax
isNaN(value)
where value = The value to be tested
Why do we need this function?
Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not.
As we saw in this post already both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.
Examples
console.log(isNaN(-1.99)); //false
console.log(isNaN(4-2)); //false
console.log(isNaN(0)); //false
console.log(isNaN('1')); //false
console.log(isNaN('string')); //true
console.log(isNaN('2020/5/5')); //true
console.log(isNaN('')); //false
console.log(isNaN(true)); //false
console.log(isNaN(undefined)); //true
console.log(isNaN('NaN')); //true
console.log(isNaN(NaN)); //true
console.log(isNaN(0 / 0)); //true
JavaScript Number isNaN() Method
The Number.isNaN() method determines whether a value is NaN (Not-A-Number).
This method returns true if the value is of the type Number, and equates to NaN. Otherwise it returns false.
Examples
Number.isNaN(1) //false
Number.isNaN(-1.99) //false
Number.isNaN(4-2) //false
Number.isNaN(0) //false
Number.isNaN('1') //false
Number.isNaN('string') //false
Number.isNaN('2020/5/5') //false
Number.isNaN('') //false
Number.isNaN(true) //false
Number.isNaN(undefined) //false
Number.isNaN('NaN') //false
Number.isNaN(NaN) //true
Number.isNaN(0 / 0) //true
You must have noticed the difference but if not, let me point it out.
//function results
console.log(isNaN('string')); //true
console.log(isNaN('2020/5/5')); //true
//method results
Number.isNaN('string') //false
Number.isNaN('2020/5/5') //false
This function is different from the Number specific Number.isNaN() method.
The global isNaN() function, converts the tested value to a Number, then tests it.
Number.isNaN() does NOT convert the values to a Number, and will not return true for any value that is not of the type Number.
NOTE: Examples are from w3schools
difference functions isNaN method