Emmanuel Akinfulubi

JavaScriptBasic

Use break and continue in JavaScript loops

Beginner · 3 min read

Loops normally run from start to finish. Two keywords let you change that: break stops the loop completely, and continue skips the rest of the current turn and moves on to the next one. You use them whenever you search a list ("stop when you find it") or filter one ("skip the ones you don't want").

In this tutorial you will search a list of car plate numbers with break, filter it with continue, and then meet two traps: continue in a while loop, and trying to stop a forEach early. You need to know how for...of and while loops work, and what startsWith does (it checks how a piece of text begins).

break and continue in plain words

Think of reading down a list of names, looking for one.

  • break: you found it, so you put the list down. You don't read the rest.
  • continue: this name doesn't interest you, so you skip to the next one, but you keep reading.

JavaScript

for (const n of [1, 2, 3, 4]) {
  if (n === 3) break;
  console.log(n); // 1, then 2
}
for (const n of [1, 2, 3, 4]) {
  if (n === 3) continue;
  console.log(n); // 1, 2, then 4
}

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

78 break, continue, and the loop you cannot break

easy

Find the first plate on a list with a given prefix and stop looking. Then walk the whole list, skipping those plates. Then try the same early exit inside forEach.

Stuck? Three hints, smallest first
  1. 1. break leaves the loop; continue skips to the next turn.
  2. 2. Count how many items you actually looked at, or you cannot prove break stopped anything.
  3. 3. A return inside a forEach callback ends that call, not the walk.

Step 1: find the first match and stop

The list holds four plate numbers. Find the first one that starts with KJA, and count how many plates you looked at:

Step 1

const plates = ['LSD-114-AB', 'KJA-902-XY', 'BDG-771-KM', 'KJA-330-ZZ'];
function firstFrom(list, prefix) {
  let found = null;
  let looked = 0;
  for (const plate of list) {
    looked++;
    if (plate.startsWith(prefix)) {
      found = plate;
      break;
    }
  }
  return { found, looked };
}
console.log(firstFrom(plates, 'KJA')); // { found: 'KJA-902-XY', looked: 2 }
console.log(firstFrom(plates, 'ZZZ')); // { found: null, looked: 4 }

The looked counter is your proof. With a match, the loop stopped after two plates and never read the other two. With no match, break never runs, so all four are read and found stays null.

Step 2: skip some, keep the rest

Now build a list of every plate that does not start with KJA:

Step 2

const plates = ['LSD-114-AB', 'KJA-902-XY', 'BDG-771-KM', 'KJA-330-ZZ'];
function without(list, prefix) {
  const kept = [];
  for (const plate of list) {
    if (plate.startsWith(prefix)) continue;
    kept.push(plate);
  }
  return kept;
}
console.log(without(plates, 'KJA')); // [ 'LSD-114-AB', 'BDG-771-KM' ]

When a plate matches, continue jumps straight to the next plate, so kept.push is skipped for that one. The loop still visits every plate.

Step 3: continue in a counting for loop

A classic for loop has three parts in its header: start, condition, and update (i++). The update runs at the end of every turn, even one cut short by continue:

Step 3

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

Even numbers are skipped, and 1 + 3 + 5 + 7 + 9 is 25. continue feels safe here because the header always moves i on.

Step 4: the while loop trap

A while loop has no update in its header. You write i++ yourself, inside the body. If it comes after the continue, then on a skipped turn it never runs, i never changes, and the loop runs forever. So the update must come first:

Step 4

function oddsWhile(limit) {
  const odds = [];
  let i = 0;
  while (i < limit) {
    i++;
    if (i % 2 === 0) continue;
    odds.push(i);
  }
  return odds;
}
console.log(oddsWhile(10)); // [ 1, 3, 5, 7, 9 ]

With i++ at the very top of the body, every turn moves on, whether or not it is skipped.

Step 5: forEach can't be stopped

forEach runs a function for each item. It looks like a loop, but break isn't allowed inside it (that is a syntax error), and return only ends the current call, like continue:

Step 5

const plates = ['LSD-114-AB', 'KJA-902-XY', 'BDG-771-KM', 'KJA-330-ZZ'];
let calls = 0;
plates.forEach((plate) => {
  calls++;
  if (plate.startsWith('KJA')) return;
});
console.log(calls); // 4

All four plates were visited, two more than the break version needed. When you want to stop early, use for...of with break, or the array methods find and some, which stop as soon as they have an answer.

The full solution

The answer panel has firstFrom, without, the odd-number sum, oddsWhile and the forEach count, and prints the break result and the number of forEach calls. Its checks prove break stopped after two plates, and that forEach ran for all four. Press Run to see the output.

The answer

const plates = ['LSD-114-AB', 'KJA-902-XY', 'BDG-771-KM', 'KJA-330-ZZ'];

// break stops the loop dead. The counter proves it.
function firstFrom(list, prefix) {
  let found = null;
  let looked = 0;
  for (const plate of list) {
    looked++;
    if (plate.startsWith(prefix)) {
      found = plate;
      break;
    }
  }
  return { found, looked };
}

// continue abandons this turn only.
function without(list, prefix) {
  const kept = [];
  for (const plate of list) {
    if (plate.startsWith(prefix)) continue;
    kept.push(plate);
  }
  return kept;
}

// In a for loop, continue still runs the i++ in the header.
let oddSum = 0;
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue;
  oddSum += i;
}

// In a while loop the increment is yours, so it must come BEFORE the continue.
function oddsWhile(limit) {
  const odds = [];
  let i = 0;
  while (i < limit) {
    i++;                        // first, always, or this never finishes
    if (i % 2 === 0) continue;
    odds.push(i);
  }
  return odds;
}

// forEach cannot be broken out of. return here behaves like continue.
let calls = 0;
plates.forEach((plate) => {
  calls++;
  if (plate.startsWith('KJA')) return;
});

console.log('break:', firstFrom(plates, 'KJA'));
console.log('forEach visited', calls, 'plates');

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('break stops at the first match', firstFrom(plates, 'KJA').found, 'KJA-902-XY');
test('and it really stopped: two read, not four', firstFrom(plates, 'KJA').looked, 2);
test('no match means the whole list is read', firstFrom(plates, 'ZZZ'), { found: null, looked: 4 });
test('continue skips and carries on', without(plates, 'KJA'), ['LSD-114-AB', 'BDG-771-KM']);
test('continue in a for loop still runs the update', oddSum, 25);
test('in a while loop the update has to come first', oddsWhile(10), [1, 3, 5, 7, 9]);
test('forEach ran for every plate despite the early return', calls, 4);
test('which is two more than the loop that could break', calls > firstFrom(plates, 'KJA').looked, true);

break is not an optimisation, it is the difference between "find one" and "look at everything". The looked counter is there so the claim is evidence rather than assertion.

Two traps. In a while loop, continue jumps straight back to the condition, so an increment written after it never runs and the loop spins forever; in a for loop the header's update clause still fires, which is why continue feels safe there and is not safe here. And forEach has no break at all — return only ends the current callback, so all four plates were visited. When you need to stop early, use for...of, or some and find, which stop by design.

Common mistakes

  • Putting the while update after continue. The skipped turn never moves on, and the loop never ends.
  • Expecting return to stop a forEach. It only ends that one call. Use for...of or find.
  • Mixing up break and continue. break leaves the loop; continue only skips to the next turn.

Try it yourself

  1. Use plates.find((p) => p.startsWith('KJA')) and check it gives the same plate as firstFrom.
  2. Write a loop over the numbers 1 to 100 that stops at the first number divisible by both 7 and 9.
  3. Change without to skip plates starting with either of two prefixes.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.