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.
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]}`);
}
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}`);
}
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}]`);
}
}
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.
What happens when unexpected runtime errors occur? How do you prevent crashes? Proceed to: JavaScript Error Handling: Try..Catch..Finally →