break in javascript

In JavaScript, the break statement is used to terminate a loop or a switch statement. When encountered, it immediately exits the current loop or switch statement and resumes execution at the next statement following the loop or switch.

Using break in for loops

The break statement can be used in a for loop to terminate it when a certain condition is met:

index.tsx
for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}
// Output: 0 1 2 3 4
104 chars
8 lines

In the above example, the loop will terminate when i equals 5, and the output will be all numbers from 0 to 4.

Using break in while loops

Similarly to a for loop, you can also use break in a while loop:

index.tsx
let i = 0;
while (i < 10) {
  if (i === 5) {
    break;
  }
  console.log(i);
  i++;
}
// Output: 0 1 2 3 4
108 chars
10 lines

Using break in switch statements

The break statement is also used to terminate a switch statement:

index.tsx
switch (color) {
  case "red":
    console.log("You chose red.");
    break;
  case "green":
    console.log("You chose green.");
    break;
  case "blue":
    console.log("You chose blue.");
    break;
  default:
    console.log("Invalid color.");
}
251 chars
14 lines

In this example, if color is "red", the output will be "You chose red.", and the switch statement will terminate. If color is neither "red", "green", nor "blue", the default case will execute.

gistlibby LogSnag