JavaScript
This page explains how the break statement exits a loop or switch as soon as a condition is met.
Goal: stop a loop or switch at the right moment and follow the resulting control flow.
break
When JavaScript reaches break, it immediately leaves the nearest enclosing loop or switch. Execution continues with the statement after that construct.
Exit a loop
JavaScript
for (let i = 0; i < 5; i += 1) {
console.log(i);
if (i === 2) {
break;
}
}
// prints 0, 1, 2When i becomes 2, the loop ends. Values 3 and 4 are never reached.
End a switch case
JavaScript
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week");
break;
case "Tuesday":
console.log("Second day");
break;
default:
console.log("Another day");
}In a switch, break prevents execution from falling through into the next case. Without it, later cases may run until another break or the end of the switch.
Keep the exit clear
breakexits only the nearest loop or switch.- Use a clear condition so readers can see why the exit happens.
- For nested loops, a plain
breakdoes not exit every level; consider a helper function or a carefully named state instead of confusing control flow. - Use
continuewhen you want to skip to the next loop iteration rather than leave the loop.