JavaScript break, continue and Labels: Control Loops with Examples

Loops normally run until their condition becomes false. Often you want to stop earlier, for example as soon as you find the failing row, or skip items you do not care about, such as disabled tests. break and continue give you that control, and labels extend it to nested loops. In this lesson you will learn all three, why they do not work inside forEach, and the array methods that replace them.

Advertisement

📖 What You’ll Learn: break to exit a loop, continue to skip an iteration, break in while loops and switch, labeled statements for nested loops, why break and continue fail inside forEach, the alternatives some, every and find, and how to write clear early-exit loops.


⛔ break: Exit a Loop Early

Definition: the break statement immediately ends the innermost loop (or switch) it is in. Execution continues with the first statement after the loop.

📄 break.js

const rows = ["ok", "ok", "ERROR", "ok", "ok"];

for (let i = 0; i < rows.length; i++) {
  console.log(`checking row ${i}: ${rows[i]}`);
  if (rows[i] === "ERROR") {
    console.log(`first error found at row ${i}, stopping`);
    break;
  }
}
console.log("after the loop");

⌨️ Terminal

node break.js

🖥️ Output

checking row 0: ok
checking row 1: ok
checking row 2: ERROR
first error found at row 2, stopping
after the loop

Rows 3 and 4 are never checked. Stopping as soon as you have your answer saves time, which matters when each iteration is a slow network call or a page action.


⏭️ continue: Skip to the Next Iteration

Definition: the continue statement ends the current iteration and jumps to the next one. In a for loop the update step (i++) still runs.

📄 continue.js

const tests = [
  { name: "login", skip: false },
  { name: "legacy export", skip: true },
  { name: "search", skip: false },
  { name: "old report", skip: true },
  { name: "checkout", skip: false },
];

let ran = 0;
for (const test of tests) {
  if (test.skip) {
    console.log(`skipped: ${test.name}`);
    continue;
  }
  ran++;
  console.log(`running: ${test.name}`);
}
console.log(`${ran} tests ran`);

⌨️ Terminal

node continue.js

🖥️ Output

running: login
skipped: legacy export
running: search
skipped: old report
running: checkout
3 tests ran

💡 Tip: continue works like a guard clause inside a loop: handle the cases you want to skip at the top, and keep the main logic un-indented below.


🔄 break and continue in while Loops

Both statements work in while and do...while too. A common pattern is while (true) with a break when a goal is reached, plus a safety limit:

📄 while-break.js

let attempt = 0;
const MAX = 10;

while (true) {
  attempt++;
  if (attempt > MAX) {
    console.log("giving up");
    break;
  }
  if (attempt % 2 === 1) {
    console.log(`attempt ${attempt}: odd, skipping`);
    continue;
  }
  console.log(`attempt ${attempt}: checking...`);
  if (attempt === 4) {
    console.log("success on attempt", attempt);
    break;
  }
}

⌨️ Terminal

node while-break.js

🖥️ Output

attempt 1: odd, skipping
attempt 2: checking...
attempt 3: odd, skipping
attempt 4: checking...
success on attempt 4

⚠️ Watch out: In a while loop, make sure the variable the condition depends on is updated before any continue. If attempt++ were placed after the continue, the loop would never advance and would run forever.


Advertisement

🏷️ Labels: break and continue in Nested Loops

In nested loops, break and continue affect only the innermost loop. To control an outer loop, give it a label (a name followed by a colon) and use break label or continue label.

📄 labels.js

const grid = [
  ["A1", "A2", "A3"],
  ["B1", "XX", "B3"],
  ["C1", "C2", "C3"],
];

// Without a label: break only exits the inner loop
for (const row of grid) {
  for (const cell of row) {
    if (cell === "XX") break;
    console.log("inner-only:", cell);
  }
}

// With a label: break exits both loops
search: for (const row of grid) {
  for (const cell of row) {
    if (cell === "XX") {
      console.log("found XX, stopping the whole search");
      break search;
    }
    console.log("labeled:", cell);
  }
}

⌨️ Terminal

node labels.js

🖥️ Output

inner-only: A1
inner-only: A2
inner-only: A3
inner-only: B1
inner-only: C1
inner-only: C2
inner-only: C3
labeled: A1
labeled: A2
labeled: A3
labeled: B1
found XX, stopping the whole search

continue label skips to the next iteration of the labeled (outer) loop:

📄 continue-label.js

const suites = {
  smoke: ["login", "BLOCKED", "search"],
  cart: ["add item", "remove item"],
};

suites: for (const [suite, tests] of Object.entries(suites)) {
  for (const test of tests) {
    if (test === "BLOCKED") {
      console.log(`${suite}: blocked test found, skipping rest of suite`);
      continue suites;
    }
    console.log(`${suite}: ${test}`);
  }
}

⌨️ Terminal

node continue-label.js

🖥️ Output

smoke: login
smoke: blocked test found, skipping rest of suite
cart: add item
cart: remove item

💡 Tip: Labels are rare in everyday code. If you need one, consider moving the inner loop into a function and using return, which is often easier to read.


🚫 break and continue Do Not Work in forEach

forEach calls a function for each item. break and continue belong to loops, not functions, so using them inside the callback is a syntax error:

📄 foreach-break.js

const ids = [1, 2, 3];
ids.forEach((id) => {
  if (id === 2) break;
  console.log(id);
});

⌨️ Terminal

node foreach-break.js

🖥️ Output

/home/you/js-course/foreach-break.js:3
  if (id === 2) break;
                ^^^^^

SyntaxError: Illegal break statement

Node.js v26.13.0

return inside the callback only ends that one call, so it behaves like continue, never like break:

📄 foreach-return.js

[1, 2, 3, 4].forEach((n) => {
  if (n === 2) return;   // skips 2 only; the loop goes on
  console.log(n);
});

⌨️ Terminal

node foreach-return.js

🖥️ Output

1
3
4

Advertisement

🔎 Alternatives: some, every and find

Many loops with break are really searches. These array methods stop early for you and express the intent better:

MethodReturnsStops when
arr.find(fn)The first matching item, or undefinedThe callback returns truthy
arr.findIndex(fn)Its index, or -1The callback returns truthy
arr.some(fn)true if at least one item matchesThe callback returns truthy
arr.every(fn)true if all items matchThe callback returns falsy
arr.includes(v)true if the value is presentThe value is found

📄 alternatives.js

const results = [
  { test: "login", status: "passed", ms: 800 },
  { test: "search", status: "failed", ms: 1200 },
  { test: "cart", status: "passed", ms: 4300 },
];

const firstFailure = results.find((r) => r.status === "failed");
console.log("first failure:", firstFailure?.test);

console.log("any failed?", results.some((r) => r.status === "failed"));
console.log("all under 5s?", results.every((r) => r.ms < 5000));
console.log("slow test index:", results.findIndex((r) => r.ms > 3000));

⌨️ Terminal

node alternatives.js

🖥️ Output

first failure: search
any failed? true
all under 5s? true
slow test index: 2

The same “first failure” search written with a loop and break, for comparison:

📄 loop-vs-method.js

const statuses = ["passed", "failed", "passed"];
let firstFailedIndex = -1;
for (let i = 0; i < statuses.length; i++) {
  if (statuses[i] === "failed") {
    firstFailedIndex = i;
    break;
  }
}
console.log(firstFailedIndex, statuses.findIndex((s) => s === "failed"));

⌨️ Terminal

node loop-vs-method.js

🖥️ Output

1 1

🧪 Tester Scenario: Scan a Log for the First Fatal Error

This script walks through log lines, ignores debug noise with continue, counts warnings, and stops at the first fatal error with break:

📄 scan-log.js

const log = [
  "DEBUG cache warmed",
  "INFO  server started on :3000",
  "WARN  slow query 1200ms",
  "DEBUG user lookup",
  "WARN  retrying payment gateway",
  "FATAL database connection lost",
  "INFO  shutting down",
];

let warnings = 0;
let fatal = null;

for (const [lineNo, line] of log.entries()) {
  if (line.startsWith("DEBUG")) continue;     // ignore noise
  if (line.startsWith("WARN")) warnings++;
  if (line.startsWith("FATAL")) {
    fatal = { lineNo: lineNo + 1, line };
    break;                                    // nothing after this matters
  }
}

console.log(`warnings before failure: ${warnings}`);
console.log(fatal ? `first fatal at line ${fatal.lineNo}: ${fatal.line}` : "no fatal errors");

⌨️ Terminal

node scan-log.js

🖥️ Output

warnings before failure: 2
first fatal at line 6: FATAL database connection lost

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print the numbers from 1 to 20, but stop as soon as you reach the first number divisible by both 3 and 4.

Show answer

📄 practice1.js

for (let n = 1; n <= 20; n++) {
  console.log(n);
  if (n % 3 === 0 && n % 4 === 0) break;
}

🖥️ Output

1
2
3
4
5
6
7
8
9
10
11
12

Q2. Print only the odd numbers from 1 to 10 using continue.

Show answer

📄 practice2.js

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

🖥️ Output

1
3
5
7
9

Q3. Sum the valid numbers in ["5", "abc", "12", "", "8"], skipping values that are not numbers or are empty.

Show answer

📄 practice3.js

const raw = ["5", "abc", "12", "", "8"];
let sum = 0;
for (const value of raw) {
  if (value.trim() === "") continue;
  const n = Number(value);
  if (!Number.isFinite(n)) continue;
  sum += n;
}
console.log(sum);

🖥️ Output

25

Q4. Find the coordinates of the first negative number in [[3, 5], [7, -2], [-9, 1]] and stop searching once found, using a labeled break.

Show answer

📄 practice4.js

const matrix = [[3, 5], [7, -2], [-9, 1]];
let found = null;

outer: for (let r = 0; r < matrix.length; r++) {
  for (let c = 0; c < matrix[r].length; c++) {
    if (matrix[r][c] < 0) {
      found = [r, c];
      break outer;
    }
  }
}
console.log(found);

🖥️ Output

[ 1, 1 ]

Q5. Rewrite this loop using some().

let hasAdmin = false;
for (const u of users) {
  if (u.role === "admin") {
    hasAdmin = true;
    break;
  }
}
Show answer

📄 practice5.js

const users = [{ role: "tester" }, { role: "admin" }, { role: "dev" }];
const hasAdmin = users.some((u) => u.role === "admin");
console.log(hasAdmin);

🖥️ Output

true

Q6. This code never ends. Explain why and fix it.

let i = 0;
while (i < 5) {
  if (i === 2) continue;
  console.log(i);
  i++;
}
Show answer

When i is 2, continue jumps back to the condition before i++ runs, so i stays 2 forever. Increment before the continue:

📄 practice6.js

let i = 0;
while (i < 5) {
  i++;
  if (i === 3) continue;   // skip the third value
  console.log(i);
}

🖥️ Output

1
2
4
5

🧠 MCQ Quiz: break, continue and Labels

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does break do inside a loop?
  2. What does continue do?
  3. What is printed?
    for (let i = 0; i < 5; i++) {
      if (i === 3) break;
      console.log(i);
    }
  4. What is printed?
    for (let i = 0; i < 5; i++) {
      if (i === 3) continue;
      console.log(i);
    }
  5. In nested loops, which loop does a plain break exit?
  6. How do you exit both loops at once?
  7. What happens with break inside a forEach callback?
  8. What does return inside a forEach callback do?
  9. Which method returns the first item that matches a condition?
  10. Why can a continue in a while loop cause an infinite loop?

💼 Interview Questions and Answers

Q1. What is the difference between break and continue?

break terminates the whole loop (or switch) and moves on to the code after it. continue terminates only the current iteration and moves to the next one: in a for loop it runs the update expression, in while it re-checks the condition. Both affect only the innermost loop unless a label is used.

Q2. How do you break out of a forEach loop?

You cannot; break is a syntax error there and return only skips the current item. Use a for...of loop with break, or a method that stops early by design: some, every, find, findIndex. Throwing an exception to stop forEach works but is a bad practice.

Q3. What are labeled statements in JavaScript?

A label is an identifier followed by a colon placed before a statement, usually a loop: outer: for (...). break outer exits that loop and continue outer jumps to its next iteration, from inside nested loops. They are valid but uncommon; extracting the nested loop into a function with return is often clearer.

Q4. Write code to check whether every API response in a list returned status 200, stopping at the first failure.

📄 every.js

const responses = [{ url: "/a", status: 200 }, { url: "/b", status: 500 }, { url: "/c", status: 200 }];

let checked = 0;
const allOk = responses.every((r) => {
  checked++;
  return r.status === 200;
});
console.log({ allOk, checked });
console.log("first failure:", responses.find((r) => r.status !== 200)?.url);

⌨️ Terminal

node every.js

🖥️ Output

{ allOk: false, checked: 2 }
first failure: /b

every stops at /b, so only two responses are checked. find then reports which one failed.


Advertisement

❓ Frequently Asked Questions

🤔 Can I use break in an if statement?

Only if the if is inside a loop or switch; then break exits that loop or switch. A break in an if outside any loop is a syntax error (unless it targets a labeled block).

🤔 Is using break considered bad practice?

No. Stopping a search as soon as you have the answer is good practice. Prefer array methods like find or some when they express the intent more directly.

🤔 Does break work in for…of and for…in loops?

Yes. break and continue work in every loop statement: for, for...of, for...in, while and do...while.

🤔 What is the difference between break and return?

break leaves the current loop or switch; return leaves the whole function (and therefore any loop inside it) and can send back a value.


🏁 Summary

  • break exits the innermost loop or switch; continue skips to the next iteration.
  • Labels (outer: for ...) let break outer and continue outer control outer loops.
  • In while loops, update the loop variable before any continue to avoid infinite loops.
  • break/continue cannot be used in forEach; return there only skips one item.
  • For searches, find, findIndex, some and every stop early and read better.

Next, continue with Lesson 17: Functions. This completes Module 3. Module 4 starts with functions, the building blocks of every program and test.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in