What is NaN, and how do you check whether a value is NaN?
NaN means 'Not a Number' and comes from failed numeric operations like Number("abc"). It is the only value not equal to itself, so use Number.isNaN(value), which avoids the coercion done by the older global isNaN.
Explain it simply
NaN is the result you get when maths goes wrong, like trying to convert "abc" into a number. Oddly, its type is still number: it is a special number value that says "this calculation has no valid answer".
NaN has a famous quirk: it is not equal to anything, not even itself. So x === NaN is always false and is useless as a check.
There are two built-in checks:
isNaN(value)(global, old): first converts the value to a number, then checks. SoisNaN("hello")istrue, which is misleading.Number.isNaN(value)(ES6): returnstrueonly if the value is actually NaN. Use this one.
Example
const amount = Number("abc");
console.log(typeof amount); // Output: number
console.log(amount === amount); // Output: false
console.log(Number.isNaN(amount)); // Output: true
console.log(isNaN("hello")); // Output: true
console.log(Number.isNaN("hello")); // Output: false
console.log(Object.is(amount, NaN)); // Output: trueObject.is also treats NaN as equal to NaN.
What to say in the interview
"NaN is a number value meaning the result of a numeric operation is undefined, for example parseInt('abc') or 0/0. It's the only value where x !== x. I use Number.isNaN because the global isNaN coerces its argument first, so isNaN('hello') returns true even though 'hello' is a string, not NaN."
Common mistakes
- Writing
if (value === NaN), which never matches. - Using the global
isNaNto validate form input and getting confusing results for strings.