JavaScript JS Tutorial JS Objects JS Functions JS Classes JS Async JS HTML DOM JS Browser BOM JS Web APIs JS AJAX JS JSON JS vs jQuery JS Graphics



JS Break

The break statement is a control statement in JavaScript that is used to terminate a loop or switch statement. It is used to exit a loop or switch statement before its normal ending condition is met. The break statement is often used in conjunction with conditional statements to provide a way to exit a loop based on a certain condition.

Usage of JS Break Statement

The break statement is used in loops and switch statements to exit the loop or switch statement. When the break statement is encountered, the loop or switch statement is immediately terminated, and the program continues with the next statement after the loop or switch statement.

The break statement is often used in loops to exit the loop when a certain condition is met. For example, consider the following code:

for (var i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}

In this code, the for loop will iterate 10 times, but when i is equal to 5, the break statement is executed, and the loop is terminated. Therefore, the output of this code will be:

0
1
2
3
4

The break statement can also be used in switch statements to exit the switch statement. For example, consider the following code:

var day = "Monday";
switch (day) {
  case "Monday":
    console.log("Today is Monday");
    break;
  case "Tuesday":
    console.log("Today is Tuesday");
    break;
  case "Wednesday":
    console.log("Today is Wednesday");
    break;
  default:
    console.log("Today is not Monday, Tuesday, or Wednesday");
}

In this code, the switch statement checks the value of the variable day and executes the corresponding case statement. When the case statement for "Monday" is executed, the break statement is encountered, and the switch statement is terminated. Therefore, the output of this code will be:

Today is Monday

Conclusion

The break statement is a useful control statement in JavaScript that is used to terminate loops and switch statements. It provides a way to exit a loop or switch statement before its normal ending condition is met. The break statement is often used in conjunction with conditional statements to provide a way to exit a loop based on a certain condition.

References

Activity