break and continue
Leaving early.
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.

- 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.
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);
}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.
| key | value |
|---|---|
| break | stop the loop |
| continue | skip to the next round |
| Searching | break at the first match |
| Keep loops | easy 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.
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;
}
}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