Ad – 728Γ—90
πŸ”€ Control Flow

JavaScript Break and Continue – Controlling Loop Flow

break and continue give you fine-grained control over loop execution. Learn how to exit a loop early, skip specific iterations, handle nested loops with labels, and use modern array methods as cleaner alternatives.

⏱️ 14 min read 🎯 Beginner πŸ“… Updated 2026

The break Statement

break immediately exits the nearest enclosing loop or switch statement. Execution continues with the statement after the loop.

JavaScript
// Stop searching when target is found
const items = ["pen", "notebook", "laptop", "phone", "tablet"];
const target = "laptop";
let foundIndex = -1;

for (let i = 0; i < items.length; i++) {
  if (items[i] === target) {
    foundIndex = i;
    break; // No need to search further
  }
}

console.log('Found "' + target + '" at index ' + foundIndex);
// Remaining items after break are NOT visited
β–Ά Output
Found "laptop" at index 2

The continue Statement

continue skips the rest of the current iteration and jumps to the next one. The loop itself continues running.

JavaScript
// Skip null/undefined values
const data = [1, null, 3, undefined, 5, null, 7];

let sum = 0;
for (const val of data) {
  if (val == null) continue; // Skip nulls and undefineds
  sum += val;
}
console.log("Sum (skipping nulls): " + sum); // 16

// Print only even numbers
for (let i = 1; i <= 10; i++) {
  if (i % 2 !== 0) continue; // Skip odd numbers
  console.log(i);
}
β–Ά Output
Sum (skipping nulls): 16 2 4 6 8 10
πŸ’‘
continue vs if Wrapper

Instead of wrapping loop body in if (valid) { ... }, use if (!valid) continue; at the top. This is the loop version of a guard clause and keeps indentation flat.

break in switch (Recap)

Remember that break in a switch exits the switch block, not any surrounding loop. If you want to break a loop from inside a switch, use a labeled break.

JavaScript
const commands = ["move", "attack", "quit", "move"];

for (const cmd of commands) {
  switch (cmd) {
    case "move":
      console.log("Moving...");
      break; // Exits switch, NOT the for loop
    case "attack":
      console.log("Attacking!");
      break;
    case "quit":
      console.log("Quitting game.");
      // This break only exits switch
      break;
  }
}
// "quit" doesn't stop the for loop here
β–Ά Output
Moving... Attacking! Quitting game. Moving...

Labeled break – Exiting Nested Loops

Labels allow you to break out of an outer loop from inside an inner loop. Attach a label before the outer loop, then use break labelName.

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

const searchValue = 5;
let row = -1, col = -1;

outerLoop: for (let r = 0; r < matrix.length; r++) {
  for (let c = 0; c < matrix[r].length; c++) {
    if (matrix[r][c] === searchValue) {
      row = r;
      col = c;
      break outerLoop; // Exits BOTH loops at once
    }
  }
}

console.log(`Found ${searchValue} at row ${row}, col ${col}`);
β–Ά Output
Found 5 at row 1, col 1

Labeled continue

Similarly, continue labelName skips to the next iteration of the outer loop.

JavaScript
// Skip entire outer row when a negative number is found
const grid = [
  [1, 2, 3],
  [4, -1, 6],   // Has negative β€” skip whole row
  [7, 8, 9]
];

let rowSums = [];

outerLoop: for (let r = 0; r < grid.length; r++) {
  let rowSum = 0;
  for (let c = 0; c < grid[r].length; c++) {
    if (grid[r][c] < 0) {
      console.log(`Row ${r} skipped (contains negative)`);
      continue outerLoop; // Skip to next outer iteration
    }
    rowSum += grid[r][c];
  }
  rowSums.push(rowSum);
}

console.log("Row sums:", rowSums);
β–Ά Output
Row 1 skipped (contains negative) Row sums: [ 6, 24 ]

Find First Match Pattern

JavaScript
// Traditional: break when found
function findFirstEven(nums) {
  for (const n of nums) {
    if (n % 2 === 0) {
      return n; // return acts like break in a function
    }
  }
  return null;
}

console.log(findFirstEven([1, 3, 5, 4, 6])); // 4

// Modern alternative: Array.find()
const nums = [1, 3, 5, 4, 6];
const firstEven = nums.find(n => n % 2 === 0);
console.log(firstEven); // 4
β–Ά Output
4 4

return Instead of break in Functions

Inside a function, use return to exit both the loop and the function in one step β€” it is cleaner than setting a flag and breaking.

JavaScript
// With flag + break β€” verbose
function containsDuplicate(arr) {
  let found = false;
  const seen = new Set();
  for (const item of arr) {
    if (seen.has(item)) {
      found = true;
      break;
    }
    seen.add(item);
  }
  return found;
}

// With return β€” clean
function containsDuplicateClean(arr) {
  const seen = new Set();
  for (const item of arr) {
    if (seen.has(item)) return true; // Exit immediately
    seen.add(item);
  }
  return false;
}

console.log(containsDuplicateClean([1, 2, 3, 2, 4])); // true
console.log(containsDuplicateClean([1, 2, 3, 4, 5])); // false
β–Ά Output
true false

Array Method Alternatives to break

GoalLoop + break/continueArray method alternative
Find first matchfor + breakArray.find()
Find index of first matchfor + breakArray.findIndex()
Check if any matchfor + break + flagArray.some()
Check if all matchfor + break + flagArray.every()
Skip itemsfor + continueArray.filter()
JavaScript
const scores = [78, 92, 55, 88, 45, 97];

// some() β€” equivalent to loop + break + flag
const hasFailure = scores.some(s => s < 60);
console.log("Has failure:", hasFailure); // true

// every() β€” equivalent to loop + break on false
const allPassed = scores.every(s => s >= 50);
console.log("All passed (>=50):", allPassed); // true

// find() β€” cleaner than loop + break
const firstHigh = scores.find(s => s >= 90);
console.log("First score >=90:", firstHigh); // 92
β–Ά Output
Has failure: true All passed (>=50): true First score >=90: 92
Ad – 336Γ—280

πŸ‹οΈ Practical Exercise

Given an array of product objects [{name, price, inStock}]:

  1. Use a for loop with continue to build a list of in-stock products only.
  2. Use a for loop with break to find and return the first product under $20.
  3. Rewrite both using Array.filter() and Array.find().

πŸ”₯ Challenge Exercise

Write a function searchGrid(grid, target) that searches a 2D array for a value using nested for loops with a labeled break. Return { found: true, row, col } or { found: false }. Then write a version using Array.findIndex() and Array.find().

πŸ“‹ Summary

  • break exits the nearest loop or switch immediately.
  • continue skips the current iteration and moves to the next.
  • Labeled break (break outerLoop) exits a specific outer loop from inside nested loops.
  • Inside functions, return is cleaner than a flag + break pattern.
  • Array methods like find(), some(), every(), and filter() are cleaner alternatives that implicitly handle early termination.

Interview Questions

  • What is the difference between break and continue?
  • How do you break out of a nested loop in JavaScript?
  • When should you use return instead of break?
  • Why can't you use break inside a forEach callback?
  • Name array methods that internally stop early (like break) and when you'd use each.

Frequently Asked Questions

Can I use break inside a forEach?+

No. forEach is a function call, not a loop construct. break is only valid in for, while, do-while, and switch. If you need to break early, use a for...of loop or array methods like find() and some().

Are labeled breaks common in real code?+

Labeled breaks are rarely used. In most cases, extracting the nested loops into a function and using return is cleaner. Labeled breaks can be harder to read at a glance because the reader must track where the label is defined.

Does continue work in for...of and for...in?+

Yes, continue works in all loop types: classic for, for...of, for...in, while, and do...while. It skips the rest of the current iteration and proceeds to the next one.