
Break and continue statements
The break statement is used to exit a loop completely once a condition has been met, or
after x number of iterations. As such it is commonly used within an if conditional block.
Take as an example the following code:
for (let i = 0; i <= 5; i++){ console.log(i); }
This will print out the value of variable i from 0 to 5. However, what if we only want to print out till the number 3 and then exit from the loop?
for(let i = 0; i <= 5; i++){ if(i === 3){ break; } console.log(i); }
With the break statement now included, the loop executes in the following manner:
- The for-loop starts execution
- The if conditional block checks for when i will be strictly equal to the number 3
- When it is, then the break statement ensures an exit from the loop completely
- As such, only numbers from 0 to 2 are logged as the loop only executes till i is 0, 1 and 2.
See the following output to the console:
0 1 2
The continue statement will terminate the current instance of an iteration in a loop. This is better explained with an example, wherein all the numbers from 0 to 5 are logged with
except the number 3.
for (let i = 1; i <= 5; i++) { if (i === 3) { continue; } console.log(i); }
The continue keyword changes the iteration in the following manner:
- The if conditional block checks if the value of i at the current iteration is 3.
- If so, the instance of that current iteration in the loop exits by using the continue keyword.
- The rest of the loop executes as is expected starting from the next iteration, with i starting at 4.
The result will be:
1 2 4 5