The break statement “exits” a loop, while the continue statement “skips” one iteration of the loop.
You may recall encountering the break statement in a previous chapter, where it was used to exit a switch() statement. The break statement can also be utilized to exit a loop.
for (let i = 0; i < 10; i++) { if (i === 3) { break; } text += “The number is “ + i + “<br>”; } |
In the example above, the break
statement terminates the loop (“breaks” the loop) when the loop counter (i) reaches 3.
The continue statement skips the current iteration of the loop if a specified condition is met, allowing the loop to proceed with the next iteration.
In this example, it skips the value of 3.
for (let i = 0; i < 10; i++) { if (i === 3) { continue; } text += “The number is “ + i + “<br>”; } |