How do you check that a number is NaN in JavaScript?

NaN is a JavaScript property representing "Not-a-Number" value. It indicates that a value is not a legal number. JavaScript provides two methods to check for NaN values: Number.isNaN() and the global isNaN() function.

Syntax

Number.NaN
Number.isNaN(value)
isNaN(value)

Using Number.isNaN() (Recommended)

Number.isNaN() is the most reliable method as it only returns true for actual NaN values without type coercion:




    
    

Using isNaN() (Global Function)

The global isNaN() function converts values to numbers before checking, which can lead to unexpected results:




    
    

Comparison

Value Number.isNaN() isNaN() Explanation
NaN true true Both correctly identify NaN
'Hello' false true isNaN() converts to number first
undefined false true isNaN() converts undefined to NaN
'' false false Empty string converts to 0

Common Use Cases

// Checking calculation results
let result = Math.sqrt(-1);
console.log(Number.isNaN(result)); // true

// Validating parsed numbers
let userInput = parseInt("abc");
console.log(Number.isNaN(userInput)); // true

// Safe division check
let division = 0 / 0;
console.log(Number.isNaN(division)); // true
true
true
true

Conclusion

Use Number.isNaN() for accurate NaN detection as it doesn't perform type coercion. The global isNaN() function can produce unexpected results due to automatic type conversion.

Updated on: 2026-03-15T23:18:59+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements