JavaScript Tutorial

Javascript Break

The break statement in JavaScript is used to control the execution of loops and switch statements. When the break statement is encountered inside a loop or switch statement, it immediately terminates the loop or switch block and transfers control to the next statement outside of the loop or switch.

Syntax:-

label: statement;

The label can be any valid identifier. We can reference the label by using the break or continue statement.  Typically, we can use the label with nested loop such as for, do-while, and while loop.

The break statement terminates the loop immediately and passes control over the next statement after the loop.

Input:-

Output:-

In this example, the for loop increments the variable i from 1 to 10. In the body of the loop, the if statement checks if i is evenly divisible by 4. If so, the break statement is executed and the loop is terminated.

The control is passed to the next statement outside the loop that outputs the variable i to the console window.

Using break statement to exit a nested loop

We use the break statement to terminate a label statement and transfer control to the next statement following the terminated statement.

Input:-

Output:-

In the above example:-

  • First, the variable iterations are set to zero.
  • Second, both loops increase the variable i and j from 1 to 10.  In the inner loop, we increase the iteration variable and use an if statement to check both i and j equal 4. If so, the break statement terminates both loops and passes the control over the next statement following the loop.

Continue statement

There is full control to handle loop statements in JavaScript. Sometimes, a situation occurs when we require to skip some code of the loop and move to the next iteration. It can be achieved by using JavaScript's continue statement.

The continue statement skips the current iteration of a loop and goes to the next one. Note that the continue statement must always appear only in the body of a loop or you will get an error.

Input:-

Output:-

In the below example:-

  • First, the for loops increment the variable i and j from 1 to 5.
  • Second, inside the body of the innermost loop, we check if both i and j are equal to 4. If so, we output a message to the web console and jump back to the outer label. Otherwise, we output the values of i and j in each iteration.
  •  

Input:-

Output:-

 

Go back to Previous Course