8️⃣

# 4.8 Infinite Loops

## 4.8 Infinite Loops

### What Are Infinite Loops?

• When you initially work with loops, you may create infinite loops.
• An infinite loop executes indefinitely.
• An infinite loop does not stop executing because the stopping condition is never reached.

### How to Prevent Infinite Loops

To avoid such problems, make sure to properly initialize the counter, make sure the terminating condition is eventually met with the proper updates to the counter variable.

### Example

Consider the following infinite `for` loop.
``for (j = 100; j >= 5; j++)``
Do you know why is this an infinite `for` loop? Note that `j` is initialized to 100 and each time the loop is executed, we add 1. Thus, each time the for loop will execute the value of `j` will go up by 1, it will never reach 5, our stopping condition.
Consider the following infinite `while` loop.
``````let i = 2;
while (i <= 10) {
document.write (i + "<br>");
i -= 2;
}``````
In the above `while` loop, `i` will always remain less than 10 because each time the loop will be executed, `i` will be decremented by 2.

## Previous Section

7️⃣
4.7 Choosing A Loop

⚖️