Tutorials JavaScript break & continue
Ch 22 / 78
Chapter 22 Beginner 5 min read JavaScript

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.

What you'll learn
What break does and when to use it
What continue does and how it differs from break
Using break inside for, while, and switch
Using continue to skip specific iterations
Labeled statements for nested loop control
Real-world patterns and when NOT to use them

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.

break
Exit the Loop Entirely
Immediately terminates the nearest enclosing loop or switch statement. Execution continues with the first statement after the loop.
Works inside
for while do…while for…of for…in switch
continue
Skip to the Next Iteration
Skips the remainder of the current loop body and jumps directly to the loop's update expression (or condition check), starting the next iteration.
Works inside
for while do…while for…of for…in
Keyword Effect Where Execution Goes Works in switch?
break Exits the loop / switch completely First line after the loop block
Yes
continue Skips current iteration body Loop's increment / condition check
No

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.

How break flows inside a for loop
1
Loop starts — condition is checked
Initializer runs once; then the condition is evaluated before each iteration.
2
Condition met — break is hit
Some iteration's code evaluates a condition and executes break.
3
Loop exits immediately
The increment expression is NOT run. Remaining iterations are skipped entirely.
4
Execution resumes after the loop
Code after the closing } of the loop runs normally.
JavaScript — break in Loops
// ── 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"
Pro Tip
Using 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.

How continue flows inside a for loop
1
Iteration starts normally
The loop body begins executing as usual.
2
continue is hit mid-body
Any remaining statements in the loop body for this iteration are skipped.
Jumps to the increment expression
In a for loop, i++ still runs. Then the condition is re-evaluated.
4
Next iteration begins
The loop continues normally — only the current iteration's remaining body was skipped.
JavaScript — continue in Loops
// ── 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
}
continue & do…while
In a 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.

JavaScript — Labeled break & continue
// ── 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); // true
Use Labels Sparingly
Labeled statements make code harder to follow. Before reaching for a label, consider refactoring the nested loops into a separate function and using a plain return 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.

Search & Find
Exit as soon as you find the target — no wasted iterations.
Input Validation
Skip invalid entries with continue instead of deep nesting.
Login Retry
Loop until correct credentials — break on success.
Data Processing
Skip null / undefined entries to avoid runtime errors.
Game Loops
break when game over condition is detected inside the loop.
Prime Numbers
break as soon as a divisor is found — no need to continue.
JavaScript — Real-World Patterns
// ── 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: Alice

Try 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.

Live Editor
✎ Editor
👁 Preview

Common Pitfalls & Best Practices

A few gotchas to keep in mind so these powerful keywords don't introduce subtle bugs into your code.

JavaScript — Pitfalls & Best Practices
// ── ❌ 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
}
forEach Gotcha
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.
⚡
Free Resource
Download our JavaScript Cheat Sheet
All loop control, operators & patterns — one printable page.
Get Sheet
Quick Check
What does break do inside a for loop?
Quick Check
What is printed by this code? for(let i=0;i<5;i++){if(i===3)continue;console.log(i);}
Quick Check
Can you use continue inside a .forEach() callback?
Chapter Summary
  • break exits the nearest enclosing loop or switch statement immediately. Execution continues with the first line after the loop.
  • continue skips 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 while loop, always make sure the loop variable is incremented before a continue call — otherwise you'll create an infinite loop.
  • break and continue do not work inside .forEach(), .map(), or .filter() — they will throw a SyntaxError. Use return to skip, or switch to a for…of loop.
  • Use continue as a guard clause to reduce nesting — fail fast at the top of the loop body rather than wrapping your logic in deep if blocks.
  • Avoid overusing labels — they reduce readability. Prefer extracting nested loops into a function and using return to exit early.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel