DEV Community

Cover image for JavaScript:     Number.isNaN() vs isNaN()
Nicolas Rodriguez
Nicolas Rodriguez

Posted on

JavaScript: Number.isNaN() vs isNaN()

This is a quick tutorial about Number.isNaN and isNaN() from Javascript.

Number.isNaN
Number.isNaN is a JavaScript method which simply finds out if whatever value passed is a number or not (NaN).

'use strict'
console.log(Number.isNaN(420));   // false, IT IS a number
console.log(Number.isNaN('NaN')); // true, it is NOT a number
Enter fullscreen mode Exit fullscreen mode

Number.isNaN is usually used in functions to determine if a value passed to a function is a number and is able to process or pass that number on to other functions. The following function is a simple if statement that uses both Number.isNaN and isNaN in order to determine if the passed value is a number and then prints out which type of of NaN is used.

'use strict'

let numberNaNvsNaN = function (yourValue) { 
    if (isNaN(yourValue)) { 
        return yourValue + ' isNaN determines it is NOT number';
    }
    if (Number.isNaN(yourValue)) { 
        return yourValue + ' Number.isNaN() determines it is NOT a number';
    }
}

console.log(numberNaNvsNaN(NaN));
console.log(typeOfNaN('5dogs'));

Enter fullscreen mode Exit fullscreen mode

It is important to remember that both Number.isNaN and isNaN will always return a boolean value, true or false.

isNaN

isNaN is also used to determine if a value is a number or not, but doesn't always behave the same way when it is passed non-numeric values because it tries to convert non-numeric values, this makes it less useful than Number.IsNaN.

// List of arguments that are NOT numbers but isNaN fails to recognize this.
console.log(isNaN(undefined));
console.log(isNaN('cat')); 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)