Skip to content
Laviyx Learn

Try

JavaScript course menu

JavaScript break and continue: Controlling Loops

Learn how to use break to exit a loop early and continue to skip to the next iteration in JavaScript, with search and filter examples, labelled statements for nested loops, and alternatives such as find and some.

Beginner6 min readUpdated
On this page

Sometimes you need to leave a loop early, or skip one repetition. break and continue do exactly that.

break: stop the loop#

break ends the loop immediately and continues with the code after it. A typical use is stopping a search once you have found what you need:

JavaScript
const orders = [120, 450, 80, 990, 300];
let firstBig = null;

for (const amount of orders) {
  console.log("checking", amount);
  if (amount > 400) {
    firstBig = amount;
    break;
  }
}
console.log("First order over 400:", firstBig);
Output
checking 120
checking 450
First order over 400: 450

The loop stops after 450; the remaining orders are never checked.

continue: skip to the next repetition#

continue skips the rest of the current repetition and moves on to the next one:

JavaScript
for (let i = 1; i <= 10; i++) {
  if (i % 3 === 0) {
    continue;   // skip multiples of 3
  }
  console.log(i);
}
Output
1
2
4
5
7
8
10

It is often used to skip invalid data:

JavaScript
const inputs = ["12", "", "abc", "7", "  "];
let total = 0;

for (const raw of inputs) {
  const value = raw.trim();
  if (value === "" || Number.isNaN(Number(value))) {
    continue;
  }
  total += Number(value);
}
console.log(total);
Output
19

Nested loops and labels#

break and continue only affect the innermost loop. To break out of an outer loop, give it a label:

JavaScript
const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

search: for (let r = 0; r < grid.length; r++) {
  for (let c = 0; c < grid[r].length; c++) {
    if (grid[r][c] === 5) {
      console.log(`Found 5 at row ${r}, column ${c}`);
      break search;
    }
  }
}
Output
Found 5 at row 1, column 1

Labels are rarely needed. Moving the nested loops into a function and using return is usually clearer.

Array methods instead#

For common searches, array methods express the intent directly and stop early on their own:

JavaScript
const orders = [120, 450, 80, 990, 300];

console.log(orders.find((amount) => amount > 400));
console.log(orders.some((amount) => amount > 900));
console.log(orders.findIndex((amount) => amount < 100));
Output
450
true
2

These are covered in Array Methods. Note that forEach cannot be stopped with break; use a for...of loop or some/find when you need to stop early.

Practice#

Practice exercise

Loop through the numbers 1 to 50. Skip numbers that are not divisible by 7, print the ones that are, and stop completely after printing the first one greater than 30.

Show solution
JavaScript
for (let n = 1; n <= 50; n++) {
  if (n % 7 !== 0) continue;
  console.log(n);
  if (n > 30) break;
}
Output
7
14
21
28
35

Key takeaway#

Finished this lesson?