Lesson 4: break and continue

Learning Objectives

By the end of this lesson, learners will:

  • Understand how to control loop behavior using break and continue
  • Learn the difference between exiting a loop vs. skipping a loop cycle
  • Practice using both statements in for, while, and do...while loops
  • Avoid common errors such as infinite loops or skipped logic

Why Do We Need break and continue?

Loops are powerful — but sometimes, you want more control over how and when they run:

  • Stop a loop early (e.g. found what you’re looking for)
  • Skip just one iteration (e.g. ignore invalid input)

JavaScript gives us two simple commands to do this:

KeywordWhat It Does
breakStops the loop entirely
continueSkips to the next loop cycle

break Statement

The break statement is used to exit a loop immediately, even if the condition is still true.

Syntax:

for (...) {
  if (condition) {
    break;
  }
}

Example: Exit Early When Found

let fruits = ["apple", "banana", "cherry", "mango"];

for (let i = 0; i < fruits.length; i++) {
  console.log("Checking:", fruits[i]);

  if (fruits[i] === "cherry") {
    console.log("Found cherry! Stopping.");
    break;
  }
}

Output:

Checking: apple  
Checking: banana  
Checking: cherry  
Found cherry! Stopping.

break stops the loop as soon as “cherry” is found.


Real-World Use Case for break

  • Stop searching when the item is found
  • Exit a loop when a user cancels input
  • Stop processing if an error is detected

continue Statement

The continue statement is used to skip the rest of the current iteration and go to the next one.

Syntax:

for (...) {
  if (condition) {
    continue;
  }
  // code that only runs if condition is false
}

Example: Skip Odd Numbers

for (let i = 1; i <= 5; i++) {
  if (i % 2 !== 0) {
    continue; // skip this loop if number is odd
  }
  console.log(i); // only even numbers will be printed
}

Output:

2  
4

The loop skips 1, 3, and 5 (all odd numbers).


Real-World Use Case for continue

  • Skip over invalid form entries
  • Ignore certain values in a list
  • Filter out undesired results

Common Mistakes

Forgetting break when it’s needed

while (true) {
  // danger: this will run forever!
  break; // add this to avoid infinite loop
}

Misplacing continue after essential code

for (let i = 1; i <= 5; i++) {
  continue;
  console.log(i); // this will never run!
}

Code after continue is skipped — so make sure important logic runs before it.


Using break and continue in while Loops

let i = 0;

while (i < 5) {
  i++;

  if (i === 3) {
    continue; // skip logging 3
  }

  if (i === 4) {
    break; // stop at 4
  }

  console.log(i);
}

Output:

1  
2