Back to course

Special Number Values: NaN and Infinity

JavaScript: The Complete '0 to Hero' Beginner Course

13. Special Number Values: NaN and Infinity

JavaScript has special values built into the Number type to represent mathematical impossibilities or limits.

1. Infinity and -Infinity

Represents a value greater than the largest possible number or less than the smallest possible number.

javascript console.log(1 / 0); // Output: Infinity console.log(-1 / 0); // Output: -Infinity console.log(2 ** 1024); // Output: Infinity (Overflow)

2. NaN (Not a Number)

NaN is the result of a mathematical operation that cannot produce a valid number.

javascript console.log('hello' / 2); // Output: NaN (You can't divide text) console.log(Math.sqrt(-1)); // Output: NaN (Cannot take square root of a negative number)

Crucial Check: You cannot test for NaN using strict equality (===).

javascript console.log(NaN === NaN); // Output: false (NaN is the only value that is not equal to itself!)

// Use this function instead: console.log(Number.isNaN('test' / 2)); // true