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, 2

When 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

Related topics