0
0
Javascriptprogramming~5 mins

Break statement in Javascript

Choose your learning style9 modes available
Introduction

The break statement stops a loop or switch early. It helps you exit when you found what you need or want to stop repeating.

When searching for a specific item in a list and you want to stop once found.
When you want to exit a loop if a certain condition happens.
When you want to stop checking cases in a switch statement after one matches.
When you want to avoid unnecessary work inside a loop once a goal is reached.
Syntax
Javascript
break;

The break statement is used alone with a semicolon.

It works inside loops (for, while, do-while) and switch statements.

Examples
This loop stops when i equals 3, so it prints 0, 1, 2 only.
Javascript
for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break;
  }
  console.log(i);
}
The while loop stops when x reaches 5, printing numbers 0 to 4.
Javascript
let x = 0;
while (x < 10) {
  if (x === 5) break;
  console.log(x);
  x++;
}
Break stops the switch after matching a case, so only one message prints.
Javascript
switch (day) {
  case 'Monday':
    console.log('Start of week');
    break;
  case 'Friday':
    console.log('End of week');
    break;
  default:
    console.log('Midweek');
}
Sample Program

This program prints numbers from 1 to 5. When i becomes 6, break stops the loop early.

Javascript
for (let i = 1; i <= 10; i++) {
  if (i === 6) {
    break;
  }
  console.log(`Number: ${i}`);
}
OutputSuccess
Important Notes

Break only stops the closest loop or switch it is inside.

Without break, loops run all their cycles unless a condition stops them.

Use break carefully to avoid skipping important code unintentionally.

Summary

The break statement stops loops or switch cases early.

It helps save time by exiting when you don't need to continue.

Use break inside loops or switch to control flow clearly.