The Break Statement
The break statement can be used to exit a loop prematurely, as well as to "jump out" of a switch statement.
Example
In this example, the loop stops when the counter (i) reaches 3:
for (let i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + "<br>";}
Here, the break statement exits the loop when i is 3.
The Continue Statement
The continue statement skips the current iteration of a loop and proceeds with the next iteration.
Example
In this example, the loop skips the iteration when the counter (i) is 3:
for (let i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>";}
Here, the continue statement skips the iteration where i is 3.
JavaScript Labels
Labels in JavaScript allow you to name code blocks, and the break and continue statements can reference these labels to control the flow of the code.
Syntax
labelName:
{ // code block}break labelName;continue labelName;
The continue statement, with or without a label reference, can only skip one loop iteration. The break statement, without a label reference, can exit a loop or a switch. With a label reference, the break statement can exit any code block.
Example
In this example, the label list is used to exit a code block before reaching the end:
const fruits = ["Apple", "Banana", "Cherry", "Date"];list: { text += fruits[0] + "<br>"; text += fruits[1] + "<br>"; break list; text += fruits[2] + "<br>"; text += fruits[3] + "<br>";}
In this example, the break statement exits the list block before fruits[2] and fruits[3] are added to text.