Flow Control
Sometimes we need to exit a loop early or skip a part of the code. For this, there are two commands: break and continue.
1. break (Stop!)
Completely stops the loop. The program moves to the next line of code below the loop.
while (true) {
let value = prompt("Enter a number (or leave empty to exit)");
if (!value) break;
}
2. continue (Skip a step)
Stops only the CURRENT iteration and immediately moves to the next one (it does the step first, then checks the condition).
for (let i = 0; i < 5; i++) {
if (i == 2) continue; // Skip the number 2
alert(i); // 0, 1, 3, 4
}
Caution
Syntax Error: You cannot use break or continue inside the ternary operator ?.
BAD: (i > 5) ? break : continue; (will throw an error).
Tip
If you find yourself using continue too often, try wrapping the code in an if. This often makes the logic simpler.