JavaScript Reference ยท Global Functions and Values
The isNaN() function
Reference for the global isNaN() function: how it converts its argument first, surprising results, and why Number.isNaN() is usually the better choice.
isNaN() converts its argument to a number and then reports whether the result is NaN. Because of that conversion step, it answers "would this become NaN as a number?", not "is this the NaN value?".
That is why isNaN("hello") is true even though the string "hello" is not NaN. For a strict check, use Number.isNaN().
isNaN("abc"); // true isNaN("12"); // false
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
isNaN(value)
| Name | Description |
|---|---|
value |
Any value. It is converted with the same rules as Number(value). |
Return value: true if the converted value is NaN, otherwise false.
Exceptions: a TypeError if the value is a Symbol or a BigInt, since neither converts to a number implicitly.
Usage notes
- The conversion causes false positives.
isNaN("abc"),isNaN(undefined)andisNaN({})are alltrue, although none of them is theNaNvalue. - Blank strings,
null,[]andfalseconvert to0, soisNaN()returnsfalsefor them. Number.isNaN()does no conversion. It istrueonly for the actualNaNvalue, which makes it the safer test after a calculation.- Equality cannot test for NaN.
x === NaNis alwaysfalse. UseNumber.isNaN(x),Object.is(x, NaN)or the idiomx !== x. - Validating input: to check that text is a usable number, combine conversion and a finite check:
Number.isFinite(Number(text)). RememberNumber("")is0. - Invalid dates are a handy case for the global function:
isNaN(date)works because a date converts to its timestamp, which isNaNfor an invalid date. - Arrays can mislead:
isNaN([5])isfalsebecause[5]converts to5.
Browser support
isNaN() is supported everywhere. Number.isNaN() is also available in all current browsers.
Related
NaN,isFinite(),Number.isNaN(),Object.is()- Lessons: Numbers, Type conversion