JavaScript — Break
Two loop controllers
break; // exit the whole loop NOW
continue; // skip to the next iteration
break
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i);
}
// 0 1 2 3 4 — stops dead at 5
continue
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i);
}
// 0 1 3 4 — only 2 is skipped
The while-loop trap
continue jumps back BEFORE your increment — infinite loop risk:
let i = 0;
while (i < 5) {
if (i === 3) continue; // 😱 i frozen at 3 forever
console.log(i);
i++;
}
Fix: increment first, or use for where the step is guaranteed:
for (let i = 0; i < 5; i++) {
if (i === 3) continue; // safe — i++ always runs
console.log(i);
}
Search pattern — stop when found
let found;
for (const user of users) {
if (user.id === targetId) {
found = user;
break; // don't waste cycles scanning the rest
}
}
// …though find() expresses this better:
const found2 = users.find(u => u.id === targetId);
Skip invalid data
for (const v of [10, null, 20, null, 30]) {
if (v === null) continue;
total += v;
}
Nested loops — nearest exit only
for (const row of grid) {
for (const cell of row) {
if (cell === null) break; // exits INNER loop only
render(cell);
}
}
Labeled loops — rare but real
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
if (j === 1) continue outer; // next OUTER iteration
console.log(i, j);
}
}
Readable alternatives usually exist (flags, functions with return, array methods) — reach for labels last.
switch uses break too
Without it, execution falls through into the next case — covered in the switch lesson.
Quick reference
| Statement | Effect | Watch out |
|---|---|---|
break | kills current loop entirely | nested → inner only |
continue | skips rest of THIS iteration | while-loops can hang |
| labels | target a specific loop | readability cost |
Mini Practice
- Stop a loop at value 5; log what printed.
- Skip evens with continue in a for AND fix the while version.
- Find-first-match with break; rewrite as find().
- Null-skipping sum over messy data.
- Nested grid scan exiting both levels with a label.
- Explain break vs continue in one sentence each.
Next: bitwise →
Related Topics
Frequently Asked Questions about Break
What is Break in JavaScript?
Break is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Break?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Break.
Why is Break important in JavaScript?
Break is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.