Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
