Episode 19 of 46

Break and Continue

Learn how to control loop execution with break and continue statements.

The break and continue statements give you more control over loop execution.

break — Exit the Loop

break immediately stops the loop and moves on to the code after it:

for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        break;  // Stop at 5
    }
    console.log(i);
}
// Output: 1, 2, 3, 4

continue — Skip to Next Iteration

continue skips the rest of the current iteration and moves to the next one:

for (let i = 1; i <= 10; i++) {
    if (i % 2 === 0) {
        continue;  // Skip even numbers
    }
    console.log(i);
}
// Output: 1, 3, 5, 7, 9

Break in While Loops

let input;
let count = 0;

while (true) {
    count++;
    if (count > 100) {
        console.log("Safety limit reached!");
        break;
    }
}
console.log("Loop ended after", count, "iterations");

Practical Examples

// Find the first number divisible by 7 and 3
for (let i = 1; i <= 100; i++) {
    if (i % 7 === 0 && i % 3 === 0) {
        console.log("Found:", i);  // 21
        break;
    }
}

// Process items, skip invalid ones
let items = [10, -5, 20, 0, 15, -3, 25];

for (let item of items) {
    if (item <= 0) {
        continue;  // Skip negative and zero values
    }
    console.log("Processing:", item);
}
// Processing: 10, 20, 15, 25