Sometimes you want to change how a loop behaves partway through. Two special keywords help:
breakstops the loop completely, right now. (You've seen it before inswitch.)continueskips the rest of this iteration and jumps to the next one.
break: get me out of here
Let's find the first number above 50 that's divisible by 7:
for (let i = 51; i <= 100; i++) {
if (i % 7 === 0) {
console.log(`Found it: ${i}`);
break;
}
}
It prints
Found it: 56
Without the break, the loop would carry on and find 63, 70, 77, and so on. With it, we stop the moment we find what we're looking for. No point searching the whole house once you've found your keys!
continue: skip this one
Let's print only the odd numbers from 1 to 10:
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // even number? skip the rest and move to the next i
}
console.log(i);
}
It prints
1 3 5 7 9
When i is even, continue jumps straight to the next iteration, skipping the console.log.
break and continue are handy, but don't overuse them. Often a clearer condition does the same job. For example, the odd-number loop could just be for (let i = 1; i <= 10; i += 2). Simpler is better!