Skip to main content

Welcome to a Grasp lesson

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

Lesson 27

Controlling Loop Execution: Break and Continue

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

Hello! In our previous lessons, we've built a solid understanding of loops (for, while, and do...while), which are fundamental for repeating tasks. You've learned how to start and stop loops based on counters and conditions.

However, sometimes you need more precise control during an iteration. What if you find what you're looking for and want to stop searching immediately? Or what if you encounter a specific item you want to ignore and just move on to the next?

This lesson introduces two powerful statements that give you this fine-grained control: break and continue. By the end of our session, you'll be able to use these statements to make your loops more efficient and powerful by terminating them early or skipping specific iterations.

The break Statement: Exiting a Loop Immediately

The break statement does exactly what its name implies: it breaks out of a loop entirely. As soon as JavaScript encounters break, it immediately terminates the loop and continues execution at the very next line of code after the loop block.

Think of it as an emergency stop button. You don't need to wait for the loop's condition to become false. If a certain condition inside the loop is met, you can use break to exit right away.

Let's watch a video that demonstrates this concept clearly.

#13 JavaScript Break and Continue | JavaScript for Beginners Course

This video from Programiz will show you how the break statement works in both for and while loops.

Watch from the beginning to 02:56. Pay close attention to how the if condition triggers the break statement and immediately stops the loop from continuing its normal iterations.

As the video showed, break is almost always used with an if statement. You don't want to break out of the loop every single time, but only when a specific condition occurs.

Let's consider a practical example. Imagine we have a list of numbers and we want to find the first number that is divisible by 7. We can loop through the list, and as soon as we find it, there's no need to check the rest of the numbers.

const numbers = [2, 13, 19, 21, 30, 49, 50];

let foundNumber;

for (let i = 0; i < numbers.length; i++) {
  const currentNumber = numbers[i];
  console.log('Checking number:', currentNumber);

  // The modulo operator (%) gives the remainder of a division.
  // If the remainder is 0, the number is evenly divisible.
  if (currentNumber % 7 === 0) {
    foundNumber = currentNumber;
    break; // Found it! Exit the loop now.
  }
}

console.log('The first number divisible by 7 is:', foundNumber); 
// Output: The first number divisible by 7 is: 21

Notice that the loop stopped checking after it found 21. The numbers 30, 49, and 50 were never even checked because the break statement terminated the loop.

This pattern is especially useful in "infinite" loops where the exit condition is checked inside the loop body rather than at the start.

Loops: while and for

The article from javascript.info provides an excellent example of using break within a while(true) loop to handle user input.

Read the section titled "Breaking the loop". Focus on the code example that asks a user for numbers. See how break provides a clean way to exit an otherwise infinite loop based on the user's input.


The continue Statement: Skipping to the Next Iteration

Now, what if you don't want to stop the loop, but just want to skip the rest of the current iteration and move to the next one? For that, we use the continue statement.

When JavaScript encounters continue, it stops executing the code in the current iteration and immediately jumps to the next one. For a for loop, it will run the update expression (e.g., i++) and then check the condition again. For a while loop, it jumps right back to checking the condition.

To visualize the difference, look at these flowcharts.

Break vs. Continue Statement Flowcharts
This image visually compares `break` and `continue`. The `break` flowchart on the right shows the execution path exiting the loop entirely. The `continue` flowchart on the left shows the path skipping the rest of the current iteration and looping back to the start of the next one.

Let's watch the next part of the Programiz video to see continue in action.

#13 JavaScript Break and Continue | JavaScript for Beginners Course

This segment explains the continue statement and contrasts its behavior with break.

Watch from 05:51 to 07:24. Notice how continue doesn't stop the loop; it just skips the console.log for a specific value and moves to the next number.

Let's write a loop that prints all numbers from 1 to 10, but skips the number 5.

for (let i = 1; i <= 10; i++) {
  if (i === 5) {
    continue; // Skip the rest of this iteration if i is 5
  }
  console.log(i);
}

The output will be:
1, 2, 3, 4, 6, 7, 8, 9, 10
(The number 5 is missing, as intended!)

A Critical Warning About continue and while Loops

Using continue in a while loop requires extra care. If you continue before the variable that controls the loop is updated, you can accidentally create an infinite loop. This is a classic bug that even experienced developers sometimes make.

JavaScript Loops Made Easy

This short clip from codeSTACKr highlights a very important pitfall when using continue inside a while loop.

Watch from 08:07 to 08:55. Pay close attention to the order of operations: the increment (i++) is placed before the continue statement to avoid an infinite loop. This is a key insight into how the loop's control flow works.

As the video explained, if the update expression (i++) comes after the continue, it will never be reached, and the loop will get stuck forever.

Correct while loop with continue:

let i = 0;
while (i < 5) {
  i++; // Update *before* the continue
  if (i === 3) {
    continue;
  }
  console.log(i); // Skips logging '3'
}
Test your understanding!

You are writing code for a checkout system. You need to calculate the total price of items in a shopping cart, but you must ignore any items with a price of 0 (which might represent a free promotional item).

Which statement (break or continue) would you use inside your loop to handle this? Why?

const cartPrices = [20, 15, 0, 30, 5];
let totalPrice = 0;

for (let i = 0; i < cartPrices.length; i++) {
  if (cartPrices[i] === 0) {
    // Should `break` or `continue` go here?
  }
  totalPrice += cartPrices[i];
}
Show answer

You should use continue.

Reasoning: You don't want to stop the entire calculation when you see a free item. You just want to ignore that specific item's price and continue to the next item in the cart to add its price to the total. Using break would incorrectly stop the calculation and give you a partial total.

The correct code would be:

const cartPrices = [20, 15, 0, 30, 5];
let totalPrice = 0;

for (let i = 0; i < cartPrices.length; i++) {
  if (cartPrices[i] === 0) {
    continue; 
  }
  totalPrice += cartPrices[i];
}

console.log(totalPrice); // Output: 70

Using break and continue Together

You can use both break and continue in the same loop to handle complex logic. Let's see a final example from the Programiz video that combines everything we've learned.

#13 JavaScript Break and Continue | JavaScript for Beginners Course

This final example demonstrates a practical scenario where a loop processes user input, using continue to skip invalid numbers (odd numbers) and break to terminate when the user signals they are done (by entering a negative number).

Watch from 07:33 to 10:20. This is a fantastic summary that shows how both statements can work together to create flexible and robust loops.


Advanced Control: Breaking from Nested Loops with Labels

What if you have a loop inside another loop (a nested loop) and you want to break out of the outer loop from within the inner loop? A normal break will only exit the inner loop.

JavaScript has a feature for this, though it's less common: labels. A label is just a name you give to a loop.

This is a more advanced concept, but since you're interested in the deeper workings of the language, it's good to be aware of.

Loops: while and for

The javascript.info article explains how to use labels to control nested loops. This is a powerful technique for specific situations.

Read the section titled "Labels for break/continue". The example of searching for coordinates in a grid is a perfect illustration of why you might need to break out of multiple loops at once.

Here is the syntax at a glance:

outerLoop: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outerLoop; // Breaks out of BOTH loops
    }
    console.log(`i=${i}, j=${j}`);
  }
}
console.log('Loop finished!');

Without the outerLoop label, break would only stop the inner j loop, and the outer i loop would continue.


Conclusion

You have now mastered two essential tools for controlling loop behavior. They allow you to write more efficient and precise code by handling special cases within your iterations.

Key Takeaways:

  • break: Immediately terminates the entire loop. Use it when you've found what you need or when a condition requires a full stop.
  • continue: Skips the current iteration and moves to the next one. Use it to ignore specific values or conditions without stopping the overall process.
  • Be extra careful with continue in while loops to avoid creating infinite loops. Always make sure the loop's control variable is updated correctly.
  • Labels can be used with break and continue for advanced control over nested loops.

Next Up:

We've seen how easy it is to accidentally create an infinite loop, especially when using while and continue. In our next lesson, we will focus entirely on this problem. We'll learn how to formally recognize and prevent infinite loops by ensuring all our loops have valid exit conditions. This is a crucial skill for writing stable and reliable programs.