break & continue

Exit a loop early or skip an iteration.

Syntaxbreak; continue;

Two keywords give you fine control inside loops:

  • break β€” stops the loop completely.
  • continue β€” skips the rest of the current pass and moves to the next.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Stop searching an array as soon as the target item is found to avoid unnecessary iterations.
  • Skip rows with missing required fields when importing a CSV without stopping the whole import.
  • Exit a polling loop early when a success condition is met before the timeout expires.

More examples

break to exit a loop early

Stops iterating as soon as the target user is found, avoiding processing the remaining elements.

Example Β· js
const users = ["alice", "bob", "carol", "dan"];
for (const user of users) {
  if (user === "carol") {
    console.log("Found:", user);
    break;
  }
}

continue to skip an iteration

Uses continue to skip rows with an empty name field and processes only valid rows.

Example Β· js
const rows = [{ name: "A", value: 10 }, { name: "", value: 5 }, { name: "C", value: 8 }];
for (const row of rows) {
  if (!row.name) continue; // skip rows with no name
  console.log(row.name, row.value);
}

break with a while poll loop

Uses an infinite while loop with break to exit as soon as a simulated success condition is met.

Example Β· js
let attempts = 0;
while (true) {
  attempts++;
  const success = attempts === 3; // simulate success on 3rd try
  if (success) {
    console.log("Succeeded on attempt", attempts);
    break;
  }
}

Discussion

  • Be the first to comment on this lesson.
break & continue β€” JavaScript | SoundsCode