break and continue

Grade 5, page 6 of 11. A one-minute read.

Sometimes you want to change how a loop behaves partway through. Two special keywords help:

  • break stops the loop completely, right now. (You've seen it before in switch.)
  • continue skips the rest of this iteration and jumps to the next one.

break: get me out of here

Let's find the first number above 50 that's divisible by 7:

JavaScript
for (let i = 51; i <= 100; i++) {
  if (i % 7 === 0) {
    console.log(`Found it: ${i}`);
    break;
  }
}

It prints

Found it: 56

Without the break, the loop would carry on and find 63, 70, 77, and so on. With it, we stop the moment we find what we're looking for. No point searching the whole house once you've found your keys!

continue: skip this one

Let's print only the odd numbers from 1 to 10:

JavaScript
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    continue; // even number? skip the rest and move to the next i
  }
  console.log(i);
}

It prints

1
3
5
7
9

When i is even, continue jumps straight to the next iteration, skipping the console.log.

Tip

break and continue are handy, but don't overuse them. Often a clearer condition does the same job. For example, the odd-number loop could just be for (let i = 1; i <= 10; i += 2). Simpler is better!

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning