NaN and Infinity
Learn what NaN and Infinity mean and how to check for them.
NaN: Not a Number
NaN stands for Not a Number. It shows up when a number operation cannot produce a meaningful number.
Common causes:
parseInt("hello")— no number in the string.0 / 0— an indeterminate division.Number("42px")— the whole string is not a valid number.
A quirk: NaN === NaN returns false! That is why you check NaN with the Number.isNaN method.
Infinity: Endless
Infinity represents numbers too large (or, when negative, -Infinity) to fit the limit. The most common source is division by zero: 1 / 0 gives Infinity.
Watch both ends: -1 / 0 gives -Infinity. These are still of type number; typeof Infinity returns "number".
To test whether a value is finite you use Number.isFinite(x). It returns false for NaN and Infinity, and true for normal numbers.
Exercise Check a division by zero
Declare const result = 10 / 0;. Then use Number.isFinite(result) to put the finiteness test into check. Log check with console.log.
Show example solution
const result = 10 / 0;
const check = Number.isFinite(result);
console.log(check);
Test yourself
-
Which one gives NaN?
- 5 / 1
- parseInt("hello")
- 1 / 0
- Number(42)
Show answer
parseInt("hello") — Correct. "hello" holds no number, so parseInt returns NaN.
-
Check NaN safely
const bad = Number.isNaN(Number(____));Show answer
const bad = Number.isNaN(Number("abc")); -
Match each value to its meaning
- NaN
- Not a number
- Infinity
- Endless value
- Number.isNaN
- Safe NaN check
- 1 / 0
- Gives Infinity
-
What does Number.isNaN("hello") return?
console.log(Number.isNaN("hello"));- true
- undefined
- Throws an error
- false
Show answer
false — Correct. Number.isNaN checks the type first; "hello" is a string, not NaN, so it returns false.