Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 28

Preventing Infinite Loops: Ensuring Valid Exit Conditions

This lesson is built with resources from youtube.com, launchschool.com and 1 more site.

Hello! In our last lesson, we explored how break and continue give you fine-grained control over your loops. We also saw a critical pitfall: how a misplaced continue statement in a while loop can accidentally create a loop that never ends.

This lesson tackles that problem head-on. We'll dive deep into infinite loops: what they are, why they are a significant problem, and most importantly, how to recognize and prevent them. Ensuring your loops have a valid exit condition is a fundamental skill for writing stable and reliable code. By the end of this lesson, you'll be able to confidently write loops that always terminate as intended.

What is an Infinite Loop?

An infinite loop is a loop whose condition to stop is never met. As a result, it runs forever. In a web browser, this usually causes the page to become unresponsive, consume all available CPU power, and eventually freeze or crash the entire browser tab.

Let's see a dramatic, yet accurate, depiction of what happens when you run an infinite loop.

Learn JavaScript WHILE LOOPS in 8 minutes! 🔁

The video from Bro Code starts by demonstrating a while loop that doesn't have a way to exit. Pay attention to how the program gets stuck, endlessly repeating the same instruction.

Watch from 00:26 to 01:07. You'll see the consequence of a loop condition that always remains true.

As you saw, the computer will mindlessly execute the loop's instructions forever, or until the program is forcibly terminated. Our job as programmers is to provide a clear "off-ramp" for every loop we create.


The Anatomy of a Functional Loop

To understand how a loop can become infinite, it's helpful to visualize its essential components. Every loop that relies on a counter has three critical parts that must work in harmony:

  1. Initialization: A variable is created and given a starting value (e.g., let i = 0;).
  2. Condition: An expression that is checked before each iteration. If it's true, the loop runs. If it's false, the loop stops (e.g., i < 5).
  3. Update: An expression that changes the variable after each iteration, bringing it closer to making the condition false (e.g., i++).

This flowchart for a for loop illustrates this flow perfectly.

For Loop Flowcharts: Generic and Example
This flowchart breaks down a `for` loop into its key stages: Initialization (`i=1`), Condition Test (`i<=5 ?`), the Loop Body, and the Increment (`i++`). The loop continues as long as the condition is true and exits when it becomes false.

An infinite loop occurs when this cycle is broken, most commonly because the Update step is missing or the Condition can never become false.


Common Causes of Infinite Loops and How to Prevent Them

Let's examine the most common mistakes that lead to infinite loops.

Cause 1: The Loop Variable Is Never Updated

This is the most frequent cause of infinite loops, especially in while loops. If the variable in your condition never changes inside the loop, the condition's result will never change.

// DANGER: Infinite Loop!
let i = 0;
while (i < 10) {
  console.log("This will run forever!");
  // The value of 'i' is never changed. 'i < 10' is always true.
}

To fix this, you must include an operation inside the loop that modifies the variable, pushing it towards the exit condition.

// CORRECTED
let i = 0;
while (i < 10) {
  console.log(i);
  i++; // The update step ensures the loop will eventually end.
}

This short video clip clearly explains this exact scenario.

JavaScript Loops Made Easy

The video from codeSTACKr demonstrates a while loop and emphasizes the importance of the increment step (i++) to prevent the loop from running infinitely.

Watch from 06:44 to 08:07. The presenter explicitly points out that omitting the increment will lock up the browser.

Cause 2: A Flawed Exit Condition

Sometimes the variable is updated correctly, but the condition itself is logically flawed, making it impossible to ever become false.

A. Incorrect Comparison Logic

Imagine you want to count down from 10 to 1. You start i at 10 and want to stop when it reaches 0. Your condition is i > 0. However, you mistakenly write i++ instead of i--.

// DANGER: Infinite Loop!
for (let i = 10; i > 0; i++) {
  // 'i' starts at 10 and increases (11, 12, 13...).
  // It will therefore ALWAYS be greater than 0.
  console.log(i); 
}

The value of i moves away from the exit condition, not towards it. The fix is to ensure your update step aligns with your condition.

// CORRECTED
for (let i = 10; i > 0; i--) {
  console.log(i);
}

B. Using Assignment (=) Instead of Comparison (===)

This is a classic and subtle bug. In JavaScript, the single equals sign (=) is for assignment, not comparison. The expression counter = 1 does two things: it assigns the value 1 to counter, and the entire expression itself evaluates to the assigned value, which is 1. Since 1 is a "truthy" value, the loop's condition is always true.

The following article has an excellent exercise that highlights this exact problem.

Loops in JavaScript

The resource from Launch School provides a clear definition of an infinite loop and includes an exercise demonstrating a common cause. We'll use this exercise to test your understanding.

First, read the section titled "while Loops" to reinforce the concept. Then, find Exercise 3 and analyze the code snippet provided there. Before looking at the solution, try to figure out why it causes an infinite loop.

Test your understanding!

Based on the exercise from the Launch School article, why does the following code result in an infinite loop?

let counter = 0;
while (counter = 1) {
  console.log(counter);
  counter += 1;

  if (counter > 2) {
    break;
  }
}
Show answer

The infinite loop is caused by the condition in the while loop: while (counter = 1).

  1. The expression counter = 1 is an assignment. It sets the value of counter to 1 in every single iteration.
  2. This assignment expression then evaluates to the value that was assigned, which is 1.
  3. In JavaScript, 1 is a "truthy" value, so the while condition is always met, and the loop continues.
  4. Inside the loop, counter is incremented to 2 (counter += 1). However, the if (counter > 2) condition for the break statement is never met, because at the start of the next iteration, counter is immediately reset to 1 by the while condition.

The correct way to write the condition would be with a comparison operator, like while (counter === 1) or while (counter < 2), depending on the desired logic.


A Prevention Checklist

To avoid infinite loops, get into the habit of asking yourself these questions every time you write a loop:

  • Is my loop variable being updated? Inside a while or do...while loop, is there a line of code (like i++ or i--) that changes the variable used in the condition?
  • Does the update move towards the exit? If my condition is i < 10, is my update i++ (moving towards 10) or i-- (moving away)?
  • Is my condition a comparison? Am I using == or === for comparison, not the assignment operator =?
  • Can the condition ever be false? Think through the logic. Is there any possible path for the loop's condition to evaluate to false?

This next article provides a great summary of what to look out for.

Javascript 101: What Are Infinite Loops and How to Avoid Them

This article from Microverse gives a concise overview of how to avoid infinite loops in for and while loops, reinforcing the points we've just discussed.

Read the section titled "How to avoid Infinite Loops?". Focus on the bullet points and code examples for both for and do...while/while loops. This will serve as a great summary and review.


Conclusion

Mastering loops means mastering their control flow. An infinite loop is a sign that the control flow is broken. By consciously ensuring every loop has a valid and reachable exit condition, you write code that is predictable, stable, and bug-free.

Key Takeaways:

  • An infinite loop occurs when its exit condition is never met, causing the program to freeze or crash.
  • The two most common causes are:
    1. Failing to update the loop's control variable.
    2. Writing a condition that is logically flawed and can never become false (e.g., i > 0 with i++, or using = instead of ===).
  • Always verify that your loop's logic includes a clear path to termination.

Next Up:

So far, we have been manually managing counters with for and while loops (let i = 0; i < length; i++). This is powerful but, as we've seen, can be prone to errors. In our next lesson, we will learn about the for...of loop, a more modern and often safer way to iterate over data structures like strings and arrays, which can help you avoid many of the counter-related bugs we've discussed today.