JavaScript Break and Continue

The break and continue statements give you fine-grained control inside loops by stopping them early or skipping individual iterations.

Changing the flow of a loop

Sometimes a loop should not run to its natural end. You might find the item you were searching for and want to stop, or you might want to ignore certain values and move straight to the next pass. JavaScript provides two keywords for exactly this: break exits the loop completely, while continue skips the rest of the current iteration and jumps to the next one.

Using break to stop early

<!DOCTYPE html>
<html>
<body>

<h2>Using break to stop early</h2>

<script>
const numbers = [4, 8, 15, 16, 23, 42];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === 16) {
    console.log("Found 16 at index", i);
    break; // stop looping immediately
  }
}
// Found 16 at index 3
</script>

</body>
</html>

Once break runs, the loop ends and execution continues with the code after it. This is efficient for searches because there is no reason to keep checking the remaining elements after you have found what you need.

Using continue to skip values

<!DOCTYPE html>
<html>
<body>

<h2>Using continue to skip values</h2>

<script>
for (let i = 1; i <= 6; i++) {
  if (i % 2 === 0) {
    continue; // skip even numbers
  }
  console.log(i);
}
// 1
// 3
// 5
</script>

</body>
</html>
  • break terminates the entire loop right away.
  • continue abandons the current iteration but keeps the loop running.
  • Both work in for, while, and do...while loops.
  • In nested loops, they affect only the innermost loop unless you use a label.
Note: With continue in a while loop, make sure the counter still gets updated before you skip. If continue jumps over the line that increments your counter, the condition may never change and you end up in an infinite loop.

break vs. continue at a glance

KeywordEffectTypical use
breakLeaves the loop entirelyStop after finding a match
continueSkips to the next iterationIgnore values that fail a check
returnExits the whole functionEnd the loop and the function together
Note: For nested loops you can attach a label to an outer loop and write break outer; or continue outer; to control it directly. Labels are rare in everyday code, but they are useful when a match in an inner loop should stop the outer loop too.

Exercise: JavaScript Loops

How many times does a do...while loop run if its condition is false from the start?