Equality operators (==, ===) do not work for detecting NaN.
Check each option:
A. value === Number.NaN
Number.NaN is just NaN.
But NaN === NaN is always false.
So this expression is never true and cannot be used to detect NaN.
B. value == NaN
Same issue. NaN == NaN is always false.
So this also never detects NaN.
C. Object.is(value, NaN)
Object.is is a more precise equality comparison method.
It treats NaN as equal to NaN: Object.is(NaN, NaN) is true.
So Object.is(value, NaN) is a valid way to detect NaN.
D. value !== value
Because NaN is the only JavaScript value that is not equal to itself , value !== value is true only when value is NaN.
This is a classic trick for NaN detection.
E. Number.isNaN(value)
Number.isNaN is the recommended modern way to check if a value is NaN without coercion .
It returns true only if value is actually the number NaN.
Therefore, the three correct ways are:
Object.is(value, NaN)
value !== value
Number.isNaN(value)
Contribute your Thoughts:
Chosen Answer:
This is a voting comment (?). You can switch to a simple comment. It is better to Upvote an existing comment if you don't have anything to add.
Submit