The break Statement
break immediately exits the nearest enclosing loop or switch statement. Execution continues with the statement after the loop.
// 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
The continue Statement
continue skips the rest of the current iteration and jumps to the next one. The loop itself continues running.
// 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);
}
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.
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
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.
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}`);
Labeled continue
Similarly, continue labelName skips to the next iteration of the outer loop.
// 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);
Find First Match Pattern
// 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
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.
// 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
Array Method Alternatives to break
| Goal | Loop + break/continue | Array method alternative |
|---|---|---|
| Find first match | for + break | Array.find() |
| Find index of first match | for + break | Array.findIndex() |
| Check if any match | for + break + flag | Array.some() |
| Check if all match | for + break + flag | Array.every() |
| Skip items | for + continue | Array.filter() |
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
ποΈ Practical Exercise
Given an array of product objects [{name, price, inStock}]:
- Use a for loop with
continueto build a list of in-stock products only. - Use a for loop with
breakto find and return the first product under $20. - Rewrite both using
Array.filter()andArray.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
breakexits the nearest loop or switch immediately.continueskips the current iteration and moves to the next.- Labeled break (
break outerLoop) exits a specific outer loop from inside nested loops. - Inside functions,
returnis cleaner than a flag + break pattern. - Array methods like
find(),some(),every(), andfilter()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
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().
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.
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.