Validating NaN in JavaScript
Checking if a number is NaN (Not a Number) in JavaScript can be tricky. This is because conventional methods such as comparing a value to NaN or using the Number.NaN constant often yield false results.
Specifically, parseFloat('geoff') == NaN will return false in Firefox's JavaScript console, even though 'geoff' is not a valid number.
Solution: Using the isNaN() Function
To accurately validate NaN, JavaScript provides the isNaN() function. Here's how you can use it:
isNaN(parseFloat("geoff"))
This will return true, indicating that the parsed value of 'geoff' is NaN.
Note: The isNaN() function can also be used to check for NaN values in non-numeric data types, such as strings.
The above is the detailed content of How Can I Reliably Check for NaN in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!