JavaScript · The language round
What is NaN and how should you check for it?
Short answer
NaN means not-a-number and is the only value that is not equal to itself. Use Number.isNaN() for a real NaN check; the global isNaN() coerces its argument first.
NaN is a numeric value that represents an invalid numeric result, such as 0 / 0 or Number("abc"). It is not an error object, and it does not throw.
0 / 0; // NaN
Number("abc"); // NaN
Math.sqrt(-1); // NaN
NaN === NaN; // false
Object.is(NaN, NaN); // trueTwo different isNaN functions
Number.isNaN(value)returns true only when the value is actually NaN- The global
isNaN(value)first converts the value to a number, soisNaN("abc")is true Object.is(value, NaN)also works and is useful when comparing values genericallyNumber.isFinite(value)rejects NaN and infinities but does not coerce
Number.isNaN(NaN); // true
Number.isNaN("abc"); // false
isNaN("abc"); // true, because "abc" becomes NaN
isNaN(""); // false, because "" becomes 0typeof NaN is "number". Do not rely on a truthiness check to detect it.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between `isNaN` and `Number.isNaN`?
- 2Why is `NaN === NaN` false?
- 3How does `Object.is` treat NaN?
- 4How do you validate numeric input from a form?
Say it in the interview
NaN is a numeric value that means an operation did not produce a valid number. It is not equal to itself, so NaN === NaN is false. The global isNaN coerces first, which makes it misleading for strings. I use Number.isNaN, or Object.is when I need a generic equality check. Number.isFinite is useful when I also want to reject Infinity.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.