Home >Web Front-end >JS Tutorial >How Can I Reliably Check for NaN in JavaScript?

How Can I Reliably Check for NaN in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 19:47:11192browse

How Can I Reliably Check for NaN in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn