Stopping or Skipping in a Loop

Two keywords let you control a loop from inside its body. break ends the whole loop right away:

for (let k = 1; k <= 6; k++) {
  if (k === 4) break;
  console.log("k =", k);
}

Output:

k = 1
k = 2
k = 3

The loop was set up to run 6 times, but when k reached 4, break stopped it. Nothing after 3 was printed. break is useful when you search for something: as soon as you find it, you can stop looking.

continue is smaller. It skips only the rest of the current pass, and the loop goes on with the next one:

for (let k = 1; k <= 6; k++) {
  if (k % 2 === 0) continue;
  console.log("odd", k);
}

Output:

odd 1
odd 3
odd 5

The even numbers still had their pass, but continue jumped over the console.log, so only the odd numbers were printed. Think of continue as "skip this one".

Both examples put the check at the top of the loop body, and the real work below it. This style keeps the code flat and easy to read. The alternative is to wrap the work inside more if blocks, which adds indentation and makes the code harder to follow.

You may notice that these if lines have no braces, although the if-else lesson said to always write them. A one-line check that only does break or continue is a common exception, because it is short and clear.

break and continue work the same way in while and for...of loops.

In the exercise, use continue to skip some numbers and break to stop the loop early.