In JavaScript, Infinity
is a special numeric value that represents positive infinity. It is a property of the global object, which means you can access it directly without any qualification.
It is a predefined global variable that represents positive infinity. Here’s the syntax:
Infinity
You can directly use the Infinity
keyword in your code wherever a numeric value is expected. For example, you can assign it to a variable, use it in mathematical calculations, or compare it with other values.
JavaScript Infinity example
Here’s an example of how you can use Infinity
in JavaScript:
console.log(Infinity); // Output: Infinity
console.log(10 / 0); // Output: Infinity
console.log(Infinity + 1); // Output: Infinity
console.log(Infinity + Infinity); // Output: Infinity
console.log(1 / Infinity); // Output: 0
console.log(-Infinity); // Output: -Infinity
console.log(-10 / 0); // Output: -Infinity
console.log(-Infinity - 1); // Output: -Infinity
Output:
As you can see from the examples, dividing a number by 0 or adding/subtracting Infinity
to/from a number always results in Infinity
. Similarly, dividing 1 by Infinity
results in 0, and the negative counterpart of Infinity
is -Infinity
.
It’s important to note that Infinity
is a property of the Number object in JavaScript, and it behaves like a number when used in mathematical operations. However, it’s not a valid number in the traditional sense, as it represents an unbounded value beyond the limits of the number system.
Here’s a practical example that demonstrates the use of Infinity
in JavaScript:
// Function to calculate the factorial of a number
function factorial(n) {
if (n === 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// Calculate factorial of a number until it reaches Infinity
var i = 0;
while (true) {
var result = factorial(i);
if (result === Infinity) {
console.log("Factorial of", i, "reaches Infinity");
break;
}
console.log("Factorial of", i, "is", result);
i++;
}
In this example, we have a function called factorial
that calculates the factorial of a given number n
. The function uses recursion to compute the factorial.
The code then enters a while
loop that continues indefinitely. Inside the loop, we calculate the factorial of each number i
and store the result in the result
variable. We check if the result is equal to Infinity
. If it is, we log a message indicating that the factorial has reached Infinity
and break out of the loop. Otherwise, we log the current factorial value and increment i
for the next iteration.
This example demonstrates that the factorial of a certain number eventually grows to a point where it exceeds the maximum representable number in JavaScript, resulting in Infinity
.
Comment if you have any doubts or suggestions on this JS basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version