This article will explain the JavaScript break and continue statements and how they are used to exit and skip iterations in loops.
JavaScript Loops
In programming, a loop iterates through a series of values, performing an action on each value it encounters.
Arrays can be looped through using the forEach method, and the for statement can be used to loop through a set of values generated by a JavaScript expression.
You may encounter situations where you want to prematurely exit a loop, or skip processing certain values in the loop.
This is what the break and continue statements allow you to do.
Using ‘break’ to Terminate a Loop
The break statement will end the execution of the current loop. No further execution will take place in the current iteration nor will any remaining iterations be processed.
The syntax is simple, just call:
break;
At the point in your code you want to break out of the loop.
‘break’ Example
Below, a for loop is constructed which will iterate the variable i through the integers 0-5.
However, it will never reach 5, as when i reaches 4, the break statement is called, causing the loop and any future iterations to terminate.
for (let i = 0; i <= 5; i++) { if (i == 4){ break; } console.log(i); }
The above code will output the following to the console:
0 1 2 3
Using ‘continue’ to Terminate Only the Current Iteration of a Loop
The continue statement is just as simple to use, but servers a slightly different purpose. Rather than completely terminating the loop, it only terminates the current iteration, so the loop will continue executing for the next value in the loop.
Again, the syntax is simple, call:
continue;
At the point in your code you wish to exit the current loop iteration at.
‘continue’ Example
Below, a loop to iterate the value of the variable i from 0-5 is again constructed.
When i is equal to 4, the continue statement is called – exiting the current iteration, so the rest of the code in the loop is not executed after the continue statement is called.
for (let i = 0; i <= 5; i++) { if (i == 4){ continue; } console.log(i); }
This will output:
0 1 2 3 5
Notice that 4 is missing, as that iteration was skipped.
‘break’ and ‘continue’ Statement Placement
The break and continue statements can be placed anywhere inside the code block for a loop – they don’t have to appear at the beginning. If the break or continue statements are placed after other lines of code within the loop, those lines will execute:
for (let i = 0; i <= 5; i++) { console.log(i); if (i == 4){ break; } }
Notice the break statement now appears after the value of i is printed, so the output will be different to the prior example:
0 1 2 3 4
The code which appears before the break statement has still been executed, with the loop broken afterwards.