AI Hints
JavaScript · Lesson 27 of 138

break and continue

Leaving early.

⏱ 2 min read▶ Video at 32:22🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Sometimes you want to stop a loop early, because you found what you were looking for. Or skip one round, and carry on with the next. Break and continue do exactly that.

break and continue
From the video: break and continue
  • Stop early
  • Skip one round
  • break and continue

Finding and skipping

In the first loop, we look for the first number divisible by seven. As soon as we find it, break stops the loop completely. In the second loop, continue skips the odd numbers, and jumps straight to the next round. Run it.

app.jsjavascript
for (let n = 20; n < 100; n++) {
  if (n % 7 === 0) {
    console.log("First multiple of 7:", n);
    break;
  }
}

for (let n = 1; n <= 10; n++) {
  if (n % 2 !== 0) continue;
  console.log("even:", n);
}
Output
First multiple of 7: 21
even: 2
even: 4
even: 6
even: 8
even: 10

Use them sparingly

Break and continue are useful, but too many can make a loop hard to follow. Often a clearer condition does the same job. Break is most useful for searching, where you stop at the first match. That saves time, especially with large lists.

keyvalue
breakstop the loop
continueskip to the next round
Searchingbreak at the first match
Keep loopseasy to follow

Searching a list

Break is perfect for searching. As soon as we find what we want, there's no point checking the rest. Here we look for the first name starting with C, and stop. Continue skips the empty strings, so they're never checked. Run it.

app.jsjavascript
const names = ["Ana", "", "Ben", "Cara", "Dan", "Cleo"];

for (const name of names) {
  if (name === "") continue;
  console.log("Checking", name);
  if (name.startsWith("C")) {
    console.log("Found:", name);
    break;
  }
}
Output
Checking Ana
Checking Ben
Checking Cara
Found: Cara

Summary

Break stops a loop, and continue skips to the next round. Next, a classic practice problem, FizzBuzz.

Key takeaways
  • break to stop
  • continue to skip
  • Clear conditions
Next up: Practice: FizzBuzz — loops and ifs