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
Release: 2024-12-05 19:47:11
Original
196 people have browsed it

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"))
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template