Home >Web Front-end >JS Tutorial >How Do I Reliably Check if a Number is NaN in JavaScript?
Determining if a Number is NaN in JavaScript
In JavaScript, when working with numeric values, it's important to verify if a number is NaN (Not-a-Number), which signifies an invalid numerical value. However, some methods commonly used for this purpose may not always yield the expected result.
Common Approaches that Fail
Attempts to compare numbers with NaN using equality operators, such as:
parseFloat('geoff') == NaN;
or
parseFloat('geoff') == Number.NaN;
will not return true in Firefox's JavaScript console. This is because NaN is a unique value that is neither equal to nor greater than or less than itself.
Reliable Method for Checking NaN
To accurately check if a number is NaN, use the isNaN() function:
isNaN(parseFloat("geoff"));
This function returns true if the specified value is NaN.
Note for Non-Numeric Values
For more comprehensive NaN checking that covers various data types, refer to:
How do you test for NaN in JavaScript?
The above is the detailed content of How Do I Reliably Check if a Number is NaN in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!