JavaScript Infinity Property
Last Updated :
13 Dec, 2024
The Infinity property in JavaScript is a global property that represents a value greater than any numerical value. It is a part of the global object and is typically returned when a number exceeds the maximum representable value in JavaScript (Number.MAX_VALUE).
This example demonstrates how Infinity is used in division, comparison, and arithmetic operations.
JavaScript
// Positive Infinity
console.log(5 / 0);
// Negative Infinity
console.log(-5 / 0);
// Comparison with a large number
console.log(Infinity > 1e10);
// Arithmetic operation
console.log(Infinity + 100);
OutputInfinity
-Infinity
true
Infinity
Syntax:
Infinity
// There is no need for a constructor or explicit definitionâit is always available in the global scope.
Key points:
- The Infinity property is a numeric value that signifies infinity.
- It is of the number data type.
- It is commonly used to represent values that exceed the floating-point range or when dividing a number by 0.
- It can be accessed without creating an instance.
- Its value cannot be changed.
- It behaves as infinity in mathematical operations.
Advantages
- Mathematical Representation: Provides a clear and direct way to represent extreme values.
- Global Accessibility: No need for imports or special declarations.
- Consistency: Offers predictable results in overflow or division by zero scenarios.
- Useful in Comparisons: Easily determines if a number is finite or infinitely large.
Limitations
- Some operations with Infinity return NaN (e.g., Infinity – Infinity or Infinity * 0).
- While conceptually useful, its applications in real-world problems are narrow.
- Operations involving Infinity often do not follow standard arithmetic rules.
- Infinity / Infinity results in NaN, making some calculations ambiguous.
Interesting Facts
- Not a Constant: Although it behaves like one, Infinity is a property of the global object and not a constant.
- Negative Infinity Exists: JavaScript also supports -Infinity to represent infinitely small values.
- Equality with Itself: Infinity === Infinity is true, making it reliable in comparisons.
- Exceeds Any Number: Even values like Number.MAX_VALUE are smaller than Infinity.
JavaScript Infinity Property – FAQ’s
What happens if you multiply Infinity by 0?
The result is NaN.
Is Infinity === Number.POSITIVE_INFINITY?
Yes, they are equivalent.
How does -Infinity behave in comparisons?
It is always less than any finite number.
Can Infinity be used in loops?
No, using it in loops results in an infinite loop, crashing the program.
What happens when you add a finite number to Infinity?
The result is still Infinity.
What is 1 / -0 in JavaScript?
-Infinity.