CodeBlanks Logo Icon CodeBlanks

break and continue

JavaScript course · Beginner · Lesson 39/133

Learn to exit a loop with break and skip an iteration with continue.

Exiting with break

The break statement exits the current loop immediately. The remaining steps are skipped and code continues after the loop. You saw it with switch; it works the same way in loops.

for (let i = 1; i <= 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}

Here when i equals 5, break runs and the loop ends. Output: 1, 2, 3, 4. Use it to end a loop early when a condition is met.

Skipping steps with continue

The continue statement skips the rest of the current step and jumps to the next iteration. It doesn't exit the loop; it just skips that one pass.

for (let i = 1; i <= 5; i++) {
  if (i % 2 === 0) {
    continue;
  }
  console.log(i);
}

Here when i is even, continue runs; console.log is skipped. Output: 1, 3, 5. So only odd numbers are printed. Use it to skip steps that meet a certain condition.

Exercise Find the first even number

Use a for loop to scan numbers 1 to 10. When i is even (i % 2 === 0), print it with console.log and exit the loop with break.

Show example solution
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    console.log(i);
    break;
  }
}

Exercise Print odd numbers

Use a for loop to scan numbers 1 to 5. When i is even, skip that step with continue. Print all odd numbers with console.log.

Show example solution
for (let i = 1; i <= 5; i++) {
  if (i % 2 === 0) {
    continue;
  }
  console.log(i);
}

Test yourself

  1. What does the break statement do?

    • Moves to the next step
    • Exits the loop completely
    • Restarts the loop
    • Throws an error
    Show answer

    Exits the loop completely — break exits the current loop immediately and skips the remaining steps.

  2. Skip even numbers

    for (let i = 1; i !== 6; i++) {
      if (i % 2 === 0) {
        ____;
      }
      console.log(i);
    }
    Show answer
    for (let i = 1; i !== 6; i++) {
      if (i % 2 === 0) {
        continue;
      }
      console.log(i);
    }

All lessons in Beginner