Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 7 of 10
break, continue & Loop Control
break exits a loop immediately. continue skips the current iteration and moves to the next. These give you fine-grained control over loop execution.
Loop Control
- break - Exits the loop immediately. No more iterations run
- continue - Skips the rest of the current iteration, goes to next iteration
- Labels - Named loops: outer: for (...). break outer; exits the named loop (for nested loops)
- Use break - When you found what you're looking for (search)
- Use continue - When you want to skip certain items (filter)
break & continue Code
// break - stop when found
const numbers = [1, 5, 3, 8, 2, 9, 4];
for (const num of numbers) {
if (num === 8) {
console.log("Found 8! Stopping.");
break; // exits loop
}
console.log("Checking:", num);
}
// continue - skip certain items
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) continue; // skip odd numbers
console.log("Even:", i); // 2, 4, 6, 8, 10
}
// Labeled break (nested loops)
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=${i}, j=${j}`);
}
}
// Real use case: find first user with admin role
const users = [
{ name: "Alice", role: "user" },
{ name: "Bob", role: "admin" },
{ name: "Charlie", role: "user" }
];
for (const user of users) {
if (user.role === "admin") {
console.log("First admin:", user.name); // Bob
break;
}
}Tip
Tip
Use break in search loops - once you find the item, stop looping. Use continue to skip invalid items early (guard clause pattern): if (!isValid) continue; - this keeps the main logic unindented and cleaner.
break, continue & Loop Control in JavaScript
Common Mistake
Warning
Using break when you meant continue (or vice versa). break exits the entire loop; continue only skips the current iteration. If your loop stops too early, you probably used break instead of continue.
Practice Task
Note
Practice loop control: (1) Loop through numbers 1-20, skip multiples of 3 using continue. (2) Search an array for a specific name and break when found. (3) Use a labeled break to exit nested loops when finding a value in a 2D array.
Quick Quiz
Key Takeaways
- break exits a loop immediately.
- break - Exits the loop immediately. No more iterations run
- continue - Skips the rest of the current iteration, goes to next iteration
- Labels - Named loops: outer: for (...). break outer; exits the named loop (for nested loops)
Finished this lesson?