Home > Web Front-end > JS Tutorial > Why Does NaN === NaN Return False in JavaScript?

Why Does NaN === NaN Return False in JavaScript?

Patricia Arquette
Release: 2025-01-25 16:37:09
Original
332 people have browsed it

Why Does NaN === NaN Return False in JavaScript?

JavaScript's peculiar behavior where NaN === NaN evaluates to false often puzzles developers. This article clarifies why this is the case and offers correct methods for NaN detection.

Understanding NaN

NaN, short for "Not-a-Number," signifies the outcome of invalid or undefined mathematical operations. Examples include:

<code class="language-javascript">console.log(0 / 0);       // NaN
console.log(Math.sqrt(-1)); // NaN</code>
Copy after login

Why the Inequality?

The IEEE 754 standard for floating-point arithmetic dictates that NaN is not equal to anything, including itself. This design prevents erroneous treatment of invalid results as if they were valid numerical values. Essentially, NaN flags an error condition and is inherently incomparable.

Reliable NaN Checks

Direct comparison fails when dealing with NaN. Instead, use these functions:

  • isNaN(): This global function checks if a value is NaN or can be coerced into NaN:
<code class="language-javascript">console.log(isNaN("abc"));    // true</code>
Copy after login
  • Number.isNaN(): This method provides a more precise check for NaN, avoiding type coercion:
<code class="language-javascript">console.log(Number.isNaN(NaN)); // true</code>
Copy after login

In Summary

The NaN === NaN comparison yields false because NaN represents an error state, not a numerical value. To accurately detect NaN, employ isNaN() or Number.isNaN() for robust and reliable code.

Source

The above is the detailed content of Why Does NaN === NaN Return False 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