The break keyword
The break keyword in JavaScript is used to stop the execution of a loop or a switch block earlier than it would finish naturally.
In loops (for, while, do...while)
break immediately ends the loop and passes control to the next line of code after the loop.
Example:
javascript
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Stops the loop when i equals 5
}
console.log(i);
}
console.log('Loop finished');Result:
javascript
0
1
2
3
4
Loop finishedHere the loop stops as soon as i becomes 5.
In a switch construct
break is used to exit the switch block after running the matching case.
Without break, execution "falls through" into the next case.
Example:
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("Another day");
}Result:
javascript
TuesdayWithout break, if case 2 had no stop, all the following cases would run until a break or the end of the block.
A note
breakcan only be used inside loops orswitch.- If you just need to skip an iteration rather than stop the loop completely, use
continue.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.