That's an excellent question! While break is certainly a key loop control statement, JavaScript also offers others that give you fine-grained control over how loops execute.
Besides break, the most common loop control statement is continue.
1. continue Statement
- Purpose: The
continuestatement skips the rest of the current iteration of the loop and immediately proceeds to the next iteration. - How it works: When
continueis encountered, the code inside the loop's current iteration, following thecontinuestatement, is skipped. However, the loop itself does not terminate. Instead, it moves to the next evaluation of the loop's condition and then to thefinal-expression(forforloops) or directly to the condition check (forwhile/do...whileloops).
Example using continue:
Let's modify our previous example to use continue instead of break if we want to skip printing only number 6, but continue with the rest of the loop.
const output = document.getElementById("output");
let htmlContent = "<h2>Using the continue statement:</h2>";
for (let i = 1; i <= 10; i++) {
if (i === 6) {
htmlContent += "Skipping number 6!<br>";
continue; // Skip the rest of this iteration, go to the next 'i'
}
htmlContent += `Current number is ${i}<br>`;
}
htmlContent += "Loop finished.";
output.innerHTML = htmlContent;
Expected Output:
Using the continue statement:
Current number is 1
Current number is 2
Current number is 3
Current number is 4
Current number is 5
Skipping number 6!
Current number is 7
Current number is 8
Current number is 9
Current number is 10
Loop finished.
As you can see, when i is 6, the message "Skipping number 6!" is added, and then continue makes the loop jump directly to i=7, bypassing Current number is 6.
break vs. continue
break: Exits the entire loop immediately. No more iterations will occur.continue: Skips only the current iteration; the loop continues with the next iteration.
Both break and continue are extremely useful for making your loops more efficient and handling specific conditions within iterations.
Do you have any questions about continue, or would you like to see another example?