40. Controlling Loops: break and continue
These two keywords give us fine-grained control over how loops execute.
1. break
The break keyword immediately stops the execution of the loop (or switch statement) and moves control to the statement immediately following the loop.
Example: Finding a target
javascript
const target = 7;
for (let i = 0; i < 10; i++) {
if (i === target) {
console.log(Found the target at index ${i}! Stopping search.);
break;
}
console.log(Checking index ${i});
}
// The loop stops when i = 7, saving unnecessary iterations.
2. continue
The continue keyword stops the current iteration of the loop and immediately jumps to the next iteration (it updates the counter/condition and restarts the block).
Example: Skipping even numbers
javascript
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip this iteration if 'i' is even
}
console.log(Odd number found: ${i});
}
// Output: 1, 3, 5, 7, 9