Home >Web Front-end >JS Tutorial >How Do I Reliably Check if a Number is NaN in JavaScript?

How Do I Reliably Check if a Number is NaN in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-12 17:04:12414browse

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!

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