JavaScript Reference ยท Number and BigInt
Number.isNaN()
Reference for Number.isNaN(): testing for the NaN value without coercion, why NaN !== NaN, and how it differs from the global isNaN() and Object.is().
Number.isNaN() returns true only if its argument is the number value NaN ("not a number"). It does no conversion, so Number.isNaN("hello") is false: the string is not NaN, it is just not a number.
NaN is the one value that is not equal to itself, so value === NaN never works as a test. This method is the clear, correct check.
Number.isNaN(value)
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
Number.isNaN(value)
| Name | Description |
|---|---|
value |
The value to test. Any type is accepted. |
Return value: true if value is of type number and is NaN; otherwise false.
Exceptions: none.
Usage notes
- No coercion. The global
isNaN()converts first, soisNaN("abc")andisNaN(undefined)aretrue, andisNaN("")isfalsebecauseNumber("")is0. Those answers are confusing; preferNumber.isNaN(). - How
NaNis produced: failed conversions (Number("abc")), invalid maths (0 / 0,Math.sqrt(-1),Infinity - Infinity), and arithmetic onundefined. - It spreads. Any arithmetic with
NaNgivesNaN, so a single bad input can turn a whole total intoNaN. Validate at the edges. - Comparisons with
NaNare alwaysfalse, evenNaN <= NaN. - Arrays and sets:
[NaN].includes(NaN)istrue, but[NaN].indexOf(NaN)is-1.SetandMaptreatNaNas equal to itself. - Equivalent checks:
Object.is(value, NaN)andvalue !== valuework too;Number.isNaN()reads better. - Not the same as invalid input in general. To check that a value is a usable number, use
Number.isFinite()as well, becauseInfinityis a number but often unwanted. - Invalid dates:
new Date("oops").getTime()isNaN; check dates withNumber.isNaN(date.getTime()).
Browser support
Supported in all current browsers; it arrived with ES2015.
Related
Number.isFinite()isNaN()NaNObject.is()- Lessons: Numbers, Type conversion