78 lines
2.5 KiB
Plaintext

== Why is this an issue?
In JavaScript, `NaN` stands for "Not-a-Number." It is a special value representing a numeric data type that is not a valid number. `NaN` is returned as a result when an arithmetic operation or mathematical function is performed, and the result is undefined or unrepresentable as a valid number.
Comparing a value with `NaN` in JavaScript can be problematic because of the way `NaN` behaves in comparison operations. The reason is that `NaN` is not equal to any value, including itself, and this behavior can lead to unexpected results.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
const a = NaN;
if (a === NaN) { // Noncompliant: Always false
console.log("a is not a number"); // This is dead code
}
if (a !== NaN) { // Noncompliant: Always true
console.log("a is not NaN"); // This statement is not necessarily true
}
----
To check if a value is `NaN`, you should use the `isNaN()` function:
[source,javascript,diff-id=1,diff-type=compliant]
----
const a = NaN;
if (isNaN(a)) {
console.log("a is not a number");
}
if (!isNaN(a)) {
console.log("a is not NaN");
}
----
Keep in mind that `isNaN()` can be a bit quirky since it tries to convert its argument into a number before checking if it is `NaN`. If the argument cannot be converted into a number, `isNaN()` will return true, which may not be the desired behavior in all cases.
Instead, you should prefer using the `Number.isNaN()` method over `isNaN()` to perform a strict check for `NaN` without any type conversion:
[source,javascript,diff-id=1,diff-type=compliant]
----
const a = NaN;
if (Number.isNaN(a)) {
console.log("a is not a number");
}
if (!Number.isNaN(a)) {
console.log("a is not NaN");
}
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN[``++NaN++``]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN[``++isNaN()++``]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN[``++Number.isNaN()++``]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Type_Conversion[Type conversion]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use a test of the format "a [!==|!=|==|===] a" instead.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]