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
Release: 2024-12-31 20:27:13
Original
384 people have browsed it

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;
Copy after login

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

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

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!

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