0
0
JavascriptHow-ToBeginner · 3 min read

How to Check if Value is NaN in JavaScript

To check if a value is NaN in JavaScript, use Number.isNaN(value) which accurately detects NaN. Avoid using the global isNaN() because it converts the value to a number first and can give misleading results.
📐

Syntax

The main method to check if a value is NaN is Number.isNaN(value). It returns true only if the value is exactly NaN. The global isNaN(value) also exists but first converts the value to a number, which can cause unexpected results.

javascript
Number.isNaN(value)
isNaN(value)
💻

Example

This example shows how Number.isNaN() correctly identifies NaN values, while isNaN() can return true for non-NaN values that convert to NaN.

javascript
console.log(Number.isNaN(NaN));        // true
console.log(Number.isNaN('hello'));    // false
console.log(isNaN(NaN));                // true
console.log(isNaN('hello'));            // true because 'hello' converts to NaN
console.log(Number.isNaN(123));         // false
console.log(isNaN(123));                 // false
Output
true false true true false false
⚠️

Common Pitfalls

A common mistake is using the global isNaN() to check for NaN. It returns true for any value that converts to NaN, like strings that are not numbers. Always prefer Number.isNaN() for accurate checks.

javascript
console.log(isNaN('abc'));          // true (wrong if checking for NaN only)
console.log(Number.isNaN('abc'));   // false (correct)

// Wrong way
if (isNaN(value)) {
  console.log('Value is NaN');
}

// Right way
if (Number.isNaN(value)) {
  console.log('Value is NaN');
}
Output
true false
📊

Quick Reference

MethodDescriptionReturns true for
Number.isNaN(value)Checks if value is exactly NaNOnly NaN
isNaN(value)Converts value to number then checks if NaNNaN and non-numeric strings

Key Takeaways

Use Number.isNaN(value) to reliably check if a value is NaN.
Avoid the global isNaN() because it converts values and can give false positives.
NaN is the only JavaScript value that is not equal to itself, so Number.isNaN() is designed to detect it precisely.
Remember that typeof NaN is 'number', so type checks alone won't detect NaN.
Use these checks when validating numeric inputs or calculations that might fail.