How to Use Number.isNaN in JavaScript: Syntax and Examples
Use
Number.isNaN(value) to check if value is the special JavaScript value NaN. It returns true only if the value is exactly NaN, unlike the global isNaN() which converts the value first.Syntax
The syntax for Number.isNaN() is simple:
Number.isNaN(value): Takes one argumentvalueto test.- Returns
trueifvalueis exactlyNaN. - Returns
falsefor all other values, including non-numbers.
javascript
Number.isNaN(value)
Example
This example shows how Number.isNaN() returns true only for NaN and false for other values:
javascript
console.log(Number.isNaN(NaN)); // true console.log(Number.isNaN('hello')); // false console.log(Number.isNaN(undefined)); // false console.log(Number.isNaN(123)); // false console.log(Number.isNaN('123')); // false console.log(Number.isNaN(0 / 0)); // true
Output
true
false
false
false
false
true
Common Pitfalls
A common mistake is confusing Number.isNaN() with the global isNaN() function. The global isNaN() converts the value to a number first, which can cause unexpected true results for non-numeric strings.
Use Number.isNaN() when you want to check if a value is exactly NaN without type coercion.
javascript
console.log(isNaN('hello')); // true (because 'hello' converts to NaN) console.log(Number.isNaN('hello')); // false (no coercion, 'hello' is not NaN)
Output
true
false
Quick Reference
| Function | Behavior | Example | Returns |
|---|---|---|---|
| Number.isNaN(value) | Checks if value is exactly NaN | Number.isNaN(NaN) | true |
| Number.isNaN(value) | Returns false for all other values | Number.isNaN('123') | false |
| isNaN(value) | Converts value to number then checks | isNaN('hello') | true |
| isNaN(value) | Can give unexpected true for non-numbers | isNaN('123') | false |
Key Takeaways
Use Number.isNaN() to check if a value is exactly NaN without type conversion.
Number.isNaN() returns false for all values except the special NaN value.
Avoid using the global isNaN() when you want precise NaN checks because it coerces values.
Number.isNaN() is a reliable way to detect NaN in modern JavaScript.
Remember that NaN is the only value in JavaScript that is not equal to itself.