JavaScript Break and Continue
The break statement leaves a loop at once. The continue statement skips the rest of the current turn.
Breaking out
The loop heads toward 10 but break ends it at 3. The value 3 itself never logs.
for (let i = 0; i < 10; i++) {
if (i === 3) {
break;
}
console.log(i);
}Skipping even numbers
continue skips the log on even turns. Only the odd numbers reach the log.
for (let i = 1; i <= 6; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}Breaking a while loop
The condition here is always true. Only the break can end this loop.
let total = 0;
let n = 1;
while (true) {
total += n;
n++;
if (total > 10) {
break;
}
}
console.log(total);Example
const names = ["Ana", "Ben", "Cid", "Dee"];
let found = "";
for (const name of names) {
if (name === "Cid") {
found = name;
break;
}
}
console.log(found);Key points
- break was first used in the switch lesson to end a case.
- break exits the whole loop, not just one turn.
- continue ends one turn early and moves to the next turn.
- Label: a name written before a loop. break can leave a labelled loop.
In this example, the loop checks each name in order. The name Cid matches the search text. The code stores the match and breaks out of the loop. The log shows the stored name.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does continue do inside a loop?