How to check if a value is NaN?
sobes.tech AI
Answer from AI
There are several ways, the most reliable is to use the Number.isNaN() function.
-
Number.isNaN(): This is the preferred method because it correctly distinguishes betweenNaNand other non-numeric values that convert toNaNwhen coerced to a number (e.g., objects).// Returns true only for NaN console.log(Number.isNaN(NaN)); // true console.log(Number.isNaN(undefined)); // false console.log(Number.isNaN({})); // false console.log(Number.isNaN('abc')); // false console.log(Number.isNaN(null)); // false console.log(Number.isNaN(0 / 0)); // true -
isNaN()(global function): This function converts the argument to a number before checking. Because of this, it can returntruefor values that are notNaNbut cannot be converted to a number. Avoid using it for strictNaNchecks.// Returns true for NaN and some non-numeric values console.log(isNaN(NaN)); // true console.log(isNaN(undefined)); // true console.log(isNaN({})); // true console.log(isNaN('abc')); // true console.log(isNaN(null)); // false -
Comparison with itself: The JavaScript specification states that
NaNis the only value that is not equal to itself. This method is reliable and works, butNumber.isNaN()is more readable.// true only if the value is NaN const value = NaN; console.log(value !== value); // true const anotherValue = 5; console.log(anotherValue !== anotherValue); // false
It is recommended to use Number.isNaN() for precise NaN checking.