JavaScript Break and Continue


1. Break statement

To leave a loop, use the break statement. A switch() statement may be "jumped out" of using it. After the loop, it ends the loop and continues running the code. The break statement ends the loop, switch, or label statement that is now in use and moves program control to the statement that comes after the terminated statement.

The program can exit a labelled statement by using the break statement, which has an optional label. The referenced label must be nested inside the break statement. Any block statement may be used as the labelled statement; a loop statement is not required to come before it. It is not possible to insert a break statement, with or without a following label, in the body of a function that is itself nested inside the loop, switch, or label statement that the break statement is intended to exit.

Example

Preview

2. Continue statement

One iteration of the loop is "jumped over" by the continue statement. It stops the current iteration of the loop and begins the subsequent one. The continue statement stops the current iteration of the current or labelled loop's statements from running and starts the loop's next iteration.

In contrast to the break statement, the continue statement does not completely end the loop's execution but rather:

  • In a while loop, it jumps back to the condition.
  • In a for loop, it jumps to the update expression.

The program can skip the current loop and instead go to the following iteration of a labelled loop statement by including an optional label in the continue statement. This labelled statement must be nested inside the continue statement in this situation.

Example

Preview