Skip to main content

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 finished

Here 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
Tuesday

Without break, if case 2 had no stop, all the following cases would run until a break or the end of the block.


A note

  • break can only be used inside loops or switch.
  • If you just need to skip an iteration rather than stop the loop completely, use continue.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.