Home >Web Front-end >JS Tutorial >How Can I Reliably Verify if a Value is NaN in JavaScript?

How Can I Reliably Verify if a Value is NaN in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-31 20:27:13419browse

How Can I Reliably Verify if a Value is NaN in JavaScript?

Verifying NaN in JavaScript: The Definitive Solution

When validating floating-point values, determining whether a number is Not a Number (NaN) can be crucial. However, attempting to compare a non-numeric value to NaN directly often leads to unexpected results.

The Pitfall

In your attempts to check for NaN using:

parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;

you may have encountered falsey outcomes. This is because these expressions attempt to coerce the non-numeric 'geoff' into a floating-point value before comparing, which results in a legitimate number (Infinity) instead of NaN.

The Solution: isNaN()

To accurately identify NaN in JavaScript, it is recommended you utilize the built-in isNaN() function. The syntax is as follows:

isNaN(value)

where value is the variable or expression you want to evaluate for NaN.

Using isNaN(), you can effectively check if a value is NaN, as demonstrated by:

isNaN(parseFloat('geoff')) // true

Note: For more comprehensive NaN checks, especially when dealing with non-numerical values, refer to the resources provided in the answer. By leveraging these approaches, you can ensure precise and robust NaN validation in your JavaScript applications.

The above is the detailed content of How Can I Reliably Verify if a Value 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
Previous article:Refresh Token in AngularNext article:Refresh Token in Angular