Break and Continue
In JavaScript, the break
and continue
statements are used to control the flow of execution in loops.
The break
statement is used to exit a loop prematurely, regardless of whether the loop condition is still true or not. When a break
statement is encountered in a loop, the loop is terminated and the program control is passed to the next statement after the loop.
Example:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // exit the loop when i is 5
}
console.log(i);
}
// Output: 0 1 2 3 4
The continue
statement is used to skip an iteration of a loop and move on to the next iteration. When a continue
statement is encountered in a loop, the current iteration is stopped and the loop condition is checked again to determine if the loop should continue.
Example:
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // skip even numbers
}
console.log(i);
}
// Output: 1 3 5 7 9
The break
and continue
statements are useful when you need to control the flow of execution in a loop based on specific conditions. However, overuse of these statements can make your code harder to read and understand. Therefore, it's important to use them judiciously and only when necessary.