break & continue
break and continue
are loop control statements that give you fine-grained power over how
a loop executes. break exits the loop entirely,
while continue skips the current iteration and
jumps to the next one — both are essential tools for writing efficient, readable loops.
break does and when to use it
continue does and how it differs from break
break inside for, while, and
switch
continue to skip specific iterations
break vs continue — At a Glance
Both keywords alter the normal top-to-bottom flow of a loop. The key difference is how much they alter it — break tears you out of the loop completely, while continue just skips the rest of the current iteration and moves on to the next one.
switch statement. Execution continues with the
first statement after the loop.
| Keyword | Effect | Where Execution Goes | Works in switch? |
|---|---|---|---|
| break | Exits the loop / switch completely | First line after the loop block |
|
| continue | Skips current iteration body | Loop's increment / condition check |
|
The break Statement
Use break when you have found
what you were looking for and there is no point iterating further —
for example, searching an array for a value, or exiting a menu loop on user input.
It saves CPU cycles by not running unnecessary iterations.
break.
} of the loop runs
normally.// ── break in a for loop ──────────────────────────────────────
for (let i = 0; i < 10; i++) {
if (i === 5) break; // stop when i reaches 5
console.log(i); // prints 0 1 2 3 4
}
console.log("Done"); // runs after the loop exits
// ── Search: find first even number ───────────────────────────
const nums = [1, 3, 7, 4, 9, 2];
let firstEven;
for (const n of nums) {
if (n % 2 === 0) {
firstEven = n;
break; // no need to keep checking
}
}
console.log(firstEven); // 4
// ── break in a while loop ────────────────────────────────────
let count = 0;
while (true) { // infinite loop — break is the only exit
count++;
if (count === 3) break;
}
console.log(count); // 3
// ── break in switch (prevents fall-through) ──────────────────
const day = "Mon";
switch (day) {
case "Mon": console.log("Start of week"); break;
case "Fri": console.log("End of week"); break;
default: console.log("Midweek");
} // "Start of week"break inside a while(true) loop is a perfectly valid
pattern — it makes the exit condition explicit inside the body rather than hidden in
the loop header. This is especially useful for menu-driven programs and event polling.
The continue Statement
Use continue when you want to
skip certain items in a loop but still process the rest.
Common use cases include filtering out invalid values, skipping blank lines,
or ignoring entries that don't match a condition — without adding deeply
nested if blocks.
for loop, i++ still runs.
Then the condition is re-evaluated.// ── Skip odd numbers, print only evens ───────────────────────
for (let i = 0; i < 10; i++) {
if (i % 2 !== 0) continue; // skip odd
console.log(i); // 0 2 4 6 8
}
// ── Filter out empty strings ──────────────────────────────────
const names = ["Alice", "", "Bob", "", "Carol"];
for (const name of names) {
if (!name) continue; // skip blank entries
console.log(name); // Alice Bob Carol
}
// ── continue in while: skip multiples of 3 ───────────────────
let i = 0;
while (i < 10) {
i++;
if (i % 3 === 0) continue; // skip 3, 6, 9
console.log(i); // 1 2 4 5 7 8 10
}
// ── Avoid deep nesting using continue (guard clause) ─────────
const users = [
{ name: "Alice", active: true },
{ name: "Bob", active: false },
{ name: "Carol", active: true },
];
// ❌ With deep nesting
for (const u of users) {
if (u.active) {
console.log(u.name); // only one indented block, but imagine more...
}
}
// ✅ With continue (guard clause — flatter, cleaner)
for (const u of users) {
if (!u.active) continue; // skip inactive users early
console.log(u.name); // Alice Carol
}do…while loop, continue jumps directly to the
condition check at the bottom — not the top of the body.
This subtle difference means the condition is re-evaluated before the
next iteration starts, just as in any other loop.
Labeled Statements
By default, break and
continue only affect the innermost loop.
A label lets you target an outer loop from inside a nested one.
Labels are rarely needed, but they are the cleanest solution when you need to break out
of two (or more) nested loops at once.
// ── Without label: break exits only the inner loop ───────────
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) break; // only breaks inner loop
console.log(i, j); // 0,0 1,0 2,0
}
}
// ── With label: break exits the outer loop ───────────────────
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outer; // exits BOTH loops
console.log(i, j);
}
}
// logs: 0,0 0,1 0,2 1,0 — then both loops stop
// ── Labeled continue: skip outer loop iteration ──────────────
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) continue outer; // skip rest of outer iteration
console.log(i, j);
}
}
// logs: 0,0 1,0 2,0 (j=1 triggers outer continue each time)
// ── Real-world: search in a 2D matrix ────────────────────────
const matrix = [[1,2,3],[4,5,6],[7,8,9]];
let found = false;
search: for (const row of matrix) {
for (const cell of row) {
if (cell === 5) { found = true; break search; }
}
}
console.log(found); // truereturn to exit early — it's almost always cleaner.
Real-World Use Cases
Here are the most common real-world scenarios where
break and continue
shine — along with a practical code example for each.
continue instead of deep
nesting.break on success.
break when game over condition is detected inside the
loop.break as soon as a divisor is found — no need to
continue.// ── 1. Search — break on first match ─────────────────────────
function findUser(users, id) {
for (const user of users) {
if (user.id === id) return user; // return also exits the loop
}
return null;
}
// ── 2. Skip null / undefined with continue ───────────────────
const data = [1, null, 3, undefined, 5];
const clean = [];
for (const item of data) {
if (item == null) continue; // skip null & undefined
clean.push(item);
}
console.log(clean); // [1, 3, 5]
// ── 3. Prime number check ─────────────────────────────────────
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false; // break as soon as divisor found
}
return true;
}
isPrime(17); // true
isPrime(18); // false
// ── 4. Process only valid form fields ────────────────────────
const fields = [
{ name: "email", value: "a@b.com", valid: true },
{ name: "phone", value: "", valid: false },
{ name: "name", value: "Alice", valid: true },
];
for (const f of fields) {
if (!f.valid) continue; // skip invalid fields
console.log(`Sending ${f.name}: ${f.value}`);
}
// Sending email: a@b.com
// Sending name: AliceTry It — Live Editor
Experiment with break and
continue directly below. Modify the values
and conditions to see exactly which iterations run and which are skipped.
Common Pitfalls & Best Practices
A few gotchas to keep in mind so these powerful keywords don't introduce subtle bugs into your code.
// ── ❌ Pitfall 1: continue does NOT work in forEach ───────────
[1, 2, 3].forEach(n => {
if (n === 2) continue; // ❌ SyntaxError: continue not in a loop
});
// ✅ Use return inside forEach to skip an iteration
[1, 2, 3].forEach(n => {
if (n === 2) return; // acts like continue inside forEach
console.log(n); // 1 3
});
// ── ❌ Pitfall 2: break does NOT work in forEach either ───────
[1, 2, 3].forEach(n => {
if (n === 2) break; // ❌ SyntaxError
});
// ✅ Use a regular for...of loop when you need break
// ── ❌ Pitfall 3: infinite loop when continue skips increment ─
let i = 0;
while (i < 5) {
if (i === 3) continue; // ❌ infinite! i never advances past 3
i++;
}
// ✅ Increment BEFORE continue
let j = 0;
while (j < 5) {
j++; // increment first
if (j === 3) continue; // now safe
console.log(j); // 1 2 4 5
}
// ── ✅ Best practice: prefer for...of + break over index tricks
const items = ["a", "b", "c", "d"];
for (const item of items) {
if (item === "c") break;
console.log(item); // a b
}break and continue are only valid inside loop
statements
(for, while, do…while, for…of,
for…in).
They do not work inside .forEach(), .map(),
or .filter() callbacks. Inside callbacks, use return to skip,
or switch to a for…of loop.
break do inside a for loop?for(let i=0;i<5;i++){if(i===3)continue;console.log(i);}
continue inside a .forEach() callback?
breakexits the nearest enclosing loop orswitchstatement immediately. Execution continues with the first line after the loop.continueskips the remaining body of the current iteration and jumps to the loop's increment expression (then re-evaluates the condition). The loop itself keeps running.- Both keywords only affect the innermost loop by default. Use
labeled statements (
label: for (...)) to target an outer loop from a nested one. - In a
whileloop, always make sure the loop variable is incremented before acontinuecall — otherwise you'll create an infinite loop. breakandcontinuedo not work inside.forEach(),.map(), or.filter()— they will throw aSyntaxError. Usereturnto skip, or switch to afor…ofloop.- Use
continueas a guard clause to reduce nesting — fail fast at the top of the loop body rather than wrapping your logic in deepifblocks. - Avoid overusing labels — they reduce readability. Prefer extracting nested loops into a
function and using
returnto exit early.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.