JavaScript Break and Continue: Loop Flow Control & Labeled Statements

During loop execution, conditions frequently arise where continuing the loop is redundant or undesirable (such as finding a target record or encountering corrupted data). The break and continue statements provide precise, surgical control over loop execution flow.

1. The break Statement (Immediate Termination)

Used to bail out of a loop completely the moment a condition is satisfied:

const userDatabase = ["Alice", "Bob", "TargetUser", "David", "Eve"];

for (let i = 0; i < userDatabase.length; i++) {
    if (userDatabase[i] === "TargetUser") {
        console.log(`Target found at index ${i}! Stopping search.`);
        break; // Stops remaining iterations immediately!
    }
    console.log(`Checking user: ${userDatabase[i]}`);
}

2. The continue Statement (Skip Current Iteration)

Used to bypass the rest of the current iteration and jump straight to the next pass:

// Print only odd numbers between 1 and 10
for (let n = 1; n <= 10; n++) {
    if (n % 2 === 0) {
        continue; // Skip even numbers!
    }
    console.log(`Odd number: ${n}`);
}

3. Labeled Statements (Breaking Out of Nested Loops)

outerGrid: for (let r = 1; r <= 3; r++) {
    for (let c = 1; c <= 3; c++) {
        if (r === 2 && c === 2) {
            console.log("Trigger hit at [2,2]! Breaking outer grid.");
            break outerGrid; // Breaks BOTH inner and outer loops!
        }
        console.log(`Cell [${r},${c}]`);
    }
}

University Exam Corner (BCA Examination Notes)

Exam Question: "What is the output of the following loop?"

for (let i = 1; i <= 4; i++) {
    if (i === 2) continue;
    if (i === 4) break;
    console.log(i);
}

Evaluation Trace:
• i = 1: neither condition met -> prints 1.
• i = 2: hits continue -> skips print.
• i = 3: neither condition met -> prints 3.
• i = 4: hits break -> loop terminates entirely.
Final Printed Output: 1 followed by 3.

Next Step

What happens when unexpected runtime errors occur? How do you prevent crashes? Proceed to: JavaScript Error Handling: Try..Catch..Finally →

Explore Related JavaScript Tutorials

Accelerate your JavaScript mastery by studying these tightly connected core tutorials:

For Loop →

Controlling loop execution flow.

While Loop →

Preventing runaway infinite loops.

Switch Statement →

Breaking out of case statements.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!