This content originally appeared on DEV Community and was authored by Yogesh Bamanier
Learn the difference between Number.isNaN() and isNaN() in JavaScript. This guide explains how each works, why they behave differently, and best practices for checking NaN
values.
1⃣ What is NaN?
NaN
stands for Not a Number. It represents a value that is mathematically invalid or unrepresentable.
Example:
let result = 0 / 0; // NaN
console.log(result); // NaN
2⃣ isNaN()
– The Classic Checker
isNaN()
is a global JavaScript function that checks if a value cannot be converted into a number.
console.log(isNaN(NaN)); // true
console.log(isNaN('hello')); // true (string cannot convert to number)
console.log(isNaN(123)); // false
Key Point: isNaN()
performs type coercion before checking, which can sometimes give unexpected results.
3⃣ Number.isNaN()
– The Modern Approach
Number.isNaN()
is more precise. It only returns true
if the value is exactly the special NaN
value.
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN('hello')); // false
console.log(Number.isNaN(123)); // false
Key Point: No type coercion occurs, making it safer for numeric checks.
4⃣ How They Differ
Feature | isNaN() |
Number.isNaN() |
---|---|---|
Type Coercion | Yes | No |
Returns true for non-numbers | Yes | No |
Use Case | General NaN check (legacy) | Precise numeric NaN check |
Example Difference:
console.log(isNaN('abc')); // true (string cannot convert to number)
console.log(Number.isNaN('abc')); // false (not the exact NaN)
5⃣ Best Practices for Developers
- Prefer
Number.isNaN()
for accurate NaN detection. - Use
isNaN()
when you want to check if a value cannot be interpreted as a number. - Remember:
NaN
is the only value in JavaScript that is not equal to itself.
console.log(NaN === NaN); // false
Conclusion
Understanding the difference between Number.isNaN()
and isNaN()
helps avoid bugs in numeric validations and ensures your JavaScript code behaves predictably.
Written by Yogesh Bamanier
This content originally appeared on DEV Community and was authored by Yogesh Bamanier