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>
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>
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>
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!