Infinity and -Infinity
What you'll learn: How JavaScript produces Infinity and -Infinity, and how to detect these special numeric values in your code.
What Are Infinity and -Infinity?
Infinity and -Infinity are special numeric values in JavaScript that represent numbers too large (or too small) to express. They behave like mathematical infinity: larger (or smaller) than any other number.
How You Get Infinity
JavaScript produces Infinity in two main ways:
- Division by zero (with a positive number):
console.log(1 / 0); // Infinity
console.log(100 / 0); // Infinity
- Numeric overflow (exceeding
Number.MAX_VALUE):
console.log(1e308 * 10); // Infinity
You get negative infinity by dividing a negative number by zero:
console.log(-1 / 0); // -Infinity
console.log(-100 / 0); // -Infinity
Detecting Infinity
Use Number.isFinite() to check if a value is a normal number (not Infinity, -Infinity, or NaN):
console.log(Number.isFinite(42)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(-Infinity)); // false
You can also compare directly:
console.log(1 / 0 === Infinity); // true
console.log(-1 / 0 === -Infinity); // true
Why It Matters
In most languages, dividing by zero causes an error. JavaScript instead returns Infinity, allowing your program to continue. This can be helpful, but it also means you must check for Infinity when doing calculations that might overflow or involve zero denominators.
Key Takeaway: Division by zero and numeric overflow produce Infinity or -Infinity in JavaScript; use Number.isFinite() to detect normal numbers and avoid unexpected infinite values in calculations.