break in switch
The break statement in a switch construct is used to interrupt execution of the switch block,
so the program does not continue into the following cases after a match is found.
Example without break
javascript
const day = 2;
switch (day) {
case 1:
console.log('Monday');
case 2:
console.log('Tuesday');
case 3:
console.log('Wednesday');
default:
console.log('Unknown day');
}Result:
javascript
Tuesday
Wednesday
Unknown dayAfter matching
case 2, the code did not stop, it "fell through" downward, running all the following blocks. This behavior is called "fall-through".
Example with break
javascript
const day = 2;
switch (day) {
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
case 3:
console.log('Wednesday');
break;
default:
console.log('Unknown day');
}Result:
javascript
TuesdayAfter running
console.log('Tuesday'), thebreakstatement exited the switch, and the remainingcases were skipped.
When break is not needed
If you deliberately want to combine several cases:
javascript
const day = 6;
switch (day) {
case 6:
case 7:
console.log('Day off');
break;
default:
console.log('Workday');
}Result:
javascript
Day offHere, "falling through" is used intentionally, so both branches run the same code.
Summary
| Situation | What break does |
|---|---|
After a case match | Stops execution of the switch |
If break is missing | The code "falls through" into the next case |
In default | Usually a trailing break is added, but it can be omitted |
| Can be used in other loops | Stops for, while, do...while |
In short
breakinswitchstops execution after the matchingcase.- Without it, all the following cases run until the end or until a
break. - It is used to avoid "falling through".
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.