By the end of this lesson, learners will:
break and continuefor, while, and do...while loopsbreak and continue?Loops are powerful — but sometimes, you want more control over how and when they run:
JavaScript gives us two simple commands to do this:
| Keyword | What It Does |
|---|---|
break | Stops the loop entirely |
continue | Skips to the next loop cycle |
break StatementThe break statement is used to exit a loop immediately, even if the condition is still true.
for (...) {
if (condition) {
break;
}
}
let fruits = ["apple", "banana", "cherry", "mango"];
for (let i = 0; i < fruits.length; i++) {
console.log("Checking:", fruits[i]);
if (fruits[i] === "cherry") {
console.log("Found cherry! Stopping.");
break;
}
}
Output:
Checking: apple
Checking: banana
Checking: cherry
Found cherry! Stopping.
break stops the loop as soon as “cherry” is found.
breakcontinue StatementThe continue statement is used to skip the rest of the current iteration and go to the next one.
for (...) {
if (condition) {
continue;
}
// code that only runs if condition is false
}
for (let i = 1; i <= 5; i++) {
if (i % 2 !== 0) {
continue; // skip this loop if number is odd
}
console.log(i); // only even numbers will be printed
}
Output:
2
4
The loop skips 1, 3, and 5 (all odd numbers).
continuebreak when it’s neededwhile (true) {
// danger: this will run forever!
break; // add this to avoid infinite loop
}
continue after essential codefor (let i = 1; i <= 5; i++) {
continue;
console.log(i); // this will never run!
}
Code after continue is skipped — so make sure important logic runs before it.
break and continue in while Loopslet i = 0;
while (i < 5) {
i++;
if (i === 3) {
continue; // skip logging 3
}
if (i === 4) {
break; // stop at 4
}
console.log(i);
}
Output:
1
2