Master JavaScript break and continue statements with ASCII flowcharts, labeled loops, real-world programs, common mistakes, and 12 interview Q&As. Perfect for beginners.
The break and continue statements are loop control mechanisms that alter the normal flow of loops. break terminates the loop entirely, while continue skips the current iteration and moves to the next one.
Overview
┌─────────────────────────────────────────────────────────┐
│ BREAK vs CONTINUE │
├─────────────────────────────┬───────────────────────────┤
│ BREAK │ CONTINUE │
├─────────────────────────────┼───────────────────────────┤
│ Exits the loop entirely │ Skips current iteration │
│ No more iterations run │ Jumps to next iteration │
│ Code after loop executes │ Remaining body skipped │
│ Works in: loops, switch │ Works in: loops only │
└─────────────────────────────┴───────────────────────────┘
The Break Statement
How Break Works
for (let i = 0; i < 10; i++)
┌────────────────────────────┐
│ ... some code ... │
│ │
│ if (condition) break; ────┼──── EXIT immediately
│ │
│ ... more code ... │ ← This is SKIPPED
└────────────────────────────┘
│
Code after the loop ◄────────┘ ← Execution continues here
Basic Break Examples
// Exit loop when target is found
for (let i = 1; i <= 10; i++) {
if (i === 6) {
console.log("Breaking at i = " + i);
break;
}
console.log("i = " + i);
}
console.log("Loop ended");
i = 1
i = 2
i = 3
i = 4
i = 5
Breaking at i = 6
Loop ended
Break in While Loop
let sum = 0;
let num = 1;
while (true) {
sum += num;
if (sum > 50) {
console.log(`Sum exceeded 50 when adding ${num}`);
console.log(`Final sum: ${sum}`);
break;
}
num++;
}
Sum exceeded 50 when adding 10
Final sum: 55
Break in Search Operations
let students = [
{ name: "Alice", grade: "A" },
{ name: "Bob", grade: "B" },
{ name: "Charlie", grade: "A" },
{ name: "Diana", grade: "C" },
{ name: "Eve", grade: "A" }
];
let firstAStudent = null;
for (let i = 0; i < students.length; i++) {
if (students[i].grade === "A") {
firstAStudent = students[i];
break; // Found first match, no need to continue
}
}
console.log("First A-grade student: " + firstAStudent.name);
First A-grade student: Alice
The Continue Statement
How Continue Works
for (let i = 0; i < 10; i++)
┌────────────────────────────┐
│ ... some code ... │
│ │
│ if (condition) continue; ─┼──── SKIP to next iteration
│ │ │
│ ... more code ... │ ← SKIPPED │
└────────────────────────────┘ │
┌────────────────────────────┐ │
│ Next iteration ◄──────────┼───────────────┘
│ ... │
└────────────────────────────┘
Basic Continue Examples
// Skip even numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue;
console.log("Odd: " + i);
}
Odd: 1
Odd: 3
Odd: 5
Odd: 7
Odd: 9
Continue in While Loop
let i = 0;
while (i < 10) {
i++;
if (i % 3 === 0) continue; // Skip multiples of 3
console.log(i);
}
⚠️ Important: In while loops, make sure the counter is updated BEFORE continue, or you'll create an infinite loop!
Continue for Data Filtering
let numbers = [12, -5, 0, 42, -3, 8, undefined, 15, null, 7];
let validSum = 0;
let count = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] == null || numbers[i] <= 0) continue;
validSum += numbers[i];
count++;
console.log(`Added ${numbers[i]}, running sum: ${validSum}`);
}
console.log(`\nTotal of ${count} valid positive numbers: ${validSum}`);
Added 12, running sum: 12
Added 42, running sum: 54
Added 8, running sum: 62
Added 15, running sum: 77
Added 7, running sum: 84
Total of 5 valid positive numbers: 84
Break and Continue in Different Loop Types
In For Loop
console.log("--- Break in for ---");
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i);
}
console.log("\n--- Continue in for ---");
for (let i = 0; i < 5; i++) {
if (i === 3) continue;
console.log(i);
}
--- Break in for ---
0
1
2
--- Continue in for ---
0
1
2
4
In For...Of Loop
let words = ["hello", "", "world", "", "javascript", ""];
console.log("Non-empty words:");
for (let word of words) {
if (word === "") continue;
console.log(" " + word);
}
Non-empty words:
hello
world
javascript
In For...In Loop
let user = {
name: "John",
_id: "abc123",
age: 30,
_internal: true,
city: "NYC"
};
console.log("Public properties:");
for (let key in user) {
if (key.startsWith("_")) continue; // Skip private properties
console.log(` ${key}: ${user[key]}`);
}
Public properties:
name: John
age: 30
city: NYC
Labeled Statements (Breaking Nested Loops)
Labels allow you to break out of or continue specific outer loops from within nested loops.
Labeled Break
console.log("Finding first pair that sums to 10:");
outerLoop:
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
if (i + j === 10) {
console.log(`Found: ${i} + ${j} = 10`);
break outerLoop; // Exits BOTH loops
}
}
}
console.log("Search complete.");
Finding first pair that sums to 10:
Found: 1 + 9 = 10
Search complete.
Without Label (Only Breaks Inner Loop)
console.log("Finding ALL pairs that sum to 10:");
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 9; j++) {
if (i + j === 10) {
console.log(` ${i} + ${j} = 10`);
break; // Only breaks inner loop
}
}
}
Finding ALL pairs that sum to 10:
1 + 9 = 10
2 + 8 = 10
3 + 7 = 10
4 + 6 = 10
5 + 5 = 10
Labeled Continue
console.log("Skipping row 2 entirely:");
outerLoop:
for (let row = 1; row <= 4; row++) {
for (let col = 1; col <= 4; col++) {
if (row === 2) continue outerLoop; // Skip entire row 2
process.stdout.write(`(${row},${col}) `);
}
console.log(""); // Newline after each row
}
console.log("");
Skipping row 2 entirely:
(1,1) (1,2) (1,3) (1,4)
(3,1) (3,2) (3,3) (3,4)
(4,1) (4,2) (4,3) (4,4)
Practical Programs
Program 1: Find Prime Numbers Using Break
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false; // break-like: early return
}
return true;
}
// Find first 10 primes
let count = 0;
let num = 2;
while (count < 10) {
if (isPrime(num)) {
console.log(`Prime #${count + 1}: ${num}`);
count++;
}
num++;
}
Prime #1: 2
Prime #2: 3
Prime #3: 5
Prime #4: 7
Prime #5: 11
Prime #6: 13
Prime #7: 17
Prime #8: 19
Prime #9: 23
Prime #10: 29
Program 2: Process Valid Data Only (Continue)
let records = [
{ id: 1, name: "Alice", score: 85 },
{ id: 2, name: "", score: 92 }, // Invalid: no name
{ id: 3, name: "Charlie", score: -5 }, // Invalid: negative score
{ id: 4, name: "Diana", score: 78 },
{ id: 5, name: "Eve", score: 95 },
{ id: null, name: "Frank", score: 88 },// Invalid: no id
];
let validCount = 0;
let totalScore = 0;
for (let i = 0; i < records.length; i++) {
let record = records[i];
// Skip invalid records
if (!record.id || !record.name || record.score < 0) {
console.log(`Skipping invalid record at index ${i}`);
continue;
}
validCount++;
totalScore += record.score;
console.log(`✓ ${record.name}: ${record.score}`);
}
console.log(`\nProcessed ${validCount} valid records`);
console.log(`Average score: ${(totalScore / validCount).toFixed(1)}`);
✓ Alice: 85
Skipping invalid record at index 1
Skipping invalid record at index 2
✓ Diana: 78
✓ Eve: 95
Skipping invalid record at index 5
Processed 3 valid records
Average score: 86.0
Program 3: Matrix Search with Labeled Break
let matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]
];
let target = 13;
let foundRow = -1, foundCol = -1;
search:
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] === target) {
foundRow = row;
foundCol = col;
break search;
}
}
}
if (foundRow !== -1) {
console.log(`Found ${target} at position [${foundRow}][${foundCol}]`);
} else {
console.log(`${target} not found in matrix`);
}
Found 13 at position [2][2]
Program 4: Rate Limiter Simulation (Continue)
let requests = [100, 200, 150, 300, 250, 180, 400, 120];
let maxPerSecond = 250;
let processed = 0;
let dropped = 0;
for (let i = 0; i < requests.length; i++) {
if (requests[i] > maxPerSecond) {
console.log(`✗ Request ${i + 1}: ${requests[i]}ms - DROPPED (exceeds limit)`);
dropped++;
continue;
}
processed++;
console.log(`✓ Request ${i + 1}: ${requests[i]}ms - Processed`);
}
console.log(`\nResults: ${processed} processed, ${dropped} dropped`);
✓ Request 1: 100ms - Processed
✓ Request 2: 200ms - Processed
✓ Request 3: 150ms - Processed
✗ Request 4: 300ms - DROPPED (exceeds limit)
✓ Request 5: 250ms - Processed
✓ Request 6: 180ms - Processed
✗ Request 7: 400ms - DROPPED (exceeds limit)
✓ Request 8: 120ms - Processed
Results: 6 processed, 2 dropped
❌ Common Mistakes
Mistake 1: Continue Before Counter Update in While
// ❌ INFINITE LOOP: i never increments when condition is true
// let i = 0;
// while (i < 10) {
// if (i === 5) continue; // i stays 5 forever!
// console.log(i);
// i++;
// }
// ✅ Update counter BEFORE continue
let i = 0;
while (i < 10) {
i++;
if (i === 5) continue;
console.log(i);
}
Mistake 2: Break Only Exits Innermost Loop
// ❌ Expecting to exit outer loop
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) break; // Only exits inner loop!
}
console.log("Outer loop still running, i = " + i);
}
// ✅ Use labeled break for outer loop
console.log("\nWith label:");
outer:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outer;
}
console.log("i = " + i);
}
console.log("Exited both loops");
Outer loop still running, i = 0
Outer loop still running, i = 1
Outer loop still running, i = 2
With label:
i = 0
Exited both loops
Mistake 3: Using Break Outside a Loop
// ❌ break outside loop/switch causes SyntaxError
// if (true) {
// break; // SyntaxError: Illegal break statement
// }
// ✅ break must be inside a loop or switch
let found = false;
for (let i = 0; i < 5; i++) {
if (i === 3) {
found = true;
break; // Valid inside loop
}
}
console.log("Found at 3:", found);
💡 Modern Alternatives
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Instead of for + break (find first match)
let firstEven = numbers.find(n => n % 2 === 0);
console.log("First even:", firstEven);
// Instead of for + continue (filter)
let odds = numbers.filter(n => n % 2 !== 0);
console.log("Odds:", odds.join(", "));
// Instead of for + break (check existence)
let hasNegative = numbers.some(n => n < 0);
console.log("Has negative:", hasNegative);
First even: 2
Odds: 1, 3, 5, 7, 9
Has negative: false
🎤 Interview Questions
Q1. What is the difference between break and continue? > break terminates the entire loop — no more iterations run after it. continue only skips the current iteration and the loop proceeds to the next one.
Q2. Can break be used outside of loops? > break can only be used inside loops (for, while, do-while) and switch statements. Using it elsewhere causes a SyntaxError: Illegal break statement.
Q3. What are labeled statements and when should you use them? > Labels (e.g., outer:) name a loop so break label or continue label can target it from nested loops. Use them when you need to exit/skip an outer loop. Prefer extracting nested loops into functions with return for cleaner code.
Q4. How does continue behave differently in for vs while loops? > In for loops, continue jumps to the update expression (e.g., i++). In while loops, it jumps directly to the condition check. This means in while loops, if counter update is placed after continue, it's skipped — causing potential infinite loops.
Q5. What is the difference between break and return? > break exits only the current loop/switch. return exits the entire function. Inside a loop within a function, return serves as both break and function exit.
Q6. Can you use break/continue in forEach? > No. forEach is a function call, not a loop statement. break causes a SyntaxError. Use return in forEach to skip an iteration (like continue), but there's no equivalent of break. Use for...of or some()/every() if you need early exit.
Q7. Does break affect the switch statement inside a loop? > A break inside a switch within a loop only exits the switch, not the loop. You need a separate mechanism (flag, label, or return) to also exit the outer loop.
Q8. What happens to the loop counter after break? > The counter retains its value at the time of break. The update expression (i++) does not run after break.
Q9. How do modern array methods replace break/continue patterns? > find() replaces "loop until found" (break), filter() replaces "skip unwanted items" (continue), some() replaces "check if any match" (break on true), every() replaces "check all match" (break on false).
Q10. Is there a performance benefit to using break? > Yes! break avoids unnecessary iterations. Searching a million-element array and breaking on first match is O(1) best case vs O(n) without break. Especially significant in nested loops (O(n²) → O(1) best case).
Q11. What is the output?
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
if (i === 4) break;
console.log(i);
}
Output: 0, 1, 3 — i=2 is skipped by continue, loop stops at i=4 via break.
Q12. What is a "flag variable" pattern as alternative to break? > Set a boolean flag when the exit condition is met, then check it in the outer loop condition:
let found = false;
for (let i = 0; i < arr.length && !found; i++) {
if (arr[i] === target) found = true;
}
🔑 Key Takeaways
| Concept | break | continue |
|---|
| What it does | Exits loop entirely | Skips current iteration |
| Works in | Loops + switch | Loops only |
| After execution | Code after loop runs | Next iteration starts |
| Labeled version | Exits specified outer loop | Skips specified outer iteration |
| Best for | Search (stop when found) | Filter (skip unwanted values) |
| Common mistake | Forgetting it only exits innermost | Forgetting to update counter before it |
💡 Memory trick: break = STOP the loop. continue = SKIP this round, next please!