JavaScript - Loop Control
In JavaScript, there are several statements that can be used to control the flow of loops. These statements allow you to skip iterations, exit loops early, or jump to the next iteration of the loop.
1. break statement: The break statement is used to exit a loop early. When the break statement is encountered inside a loop, the loop is terminated and the program control resumes at the next statement following the loop. Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}
In this example, the code logs the numbers 1 and 2 to the console, then stops when i is equal to 3, since the break statement terminates the loop.
2. continue statement: The continue statement is used to skip the current iteration of a loop and jump to the next iteration. When the continue statement is encountered inside a loop, the program control jumps to the next iteration of the loop, bypassing the remaining code in the current iteration. Example:
for (let i = 1; i <= 5; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}
In this example, the code logs the odd numbers 1, 3, and 5 to the console, since the continue statement skips the even numbers 2 and 4.
By using break and continue statements, you can fine-tune the behavior of loops in your code, allowing you to achieve more complex control structures.