Module 4: Control Flow – Conditionals and Loops
Loop Control: break and continue
break
and continue
are statements that alter the normal flow of a loop.
1. break
statement:
Immediately terminates the innermost loop (for
, while
, do...while
, or switch
) in which it appears. Execution continues with the statement following the terminated loop.
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
2. continue
statement:
Skips the remaining statements in the current iteration of the loop and proceeds to the next iteration.
for (let i = 0; i < 5; i++) { if (i === 2) { continue; // Skip iteration when i is 2 } console.log(i); } // Output: 0, 1, 3, 4 (2 is skipped)
break
and continue
are useful for controlling loop execution based on specific conditions encountered during iteration.