TypeScript Tutorial
TypeScript Break and Continue
break leaves a loop early. continue skips the rest of this iteration and starts the next.
Stop, or skip one pass
Loops run until their condition is false. Sometimes you want out sooner: you found the value, the input is bad, the count is high enough. break leaves the loop immediately. The next statement after the loop runs next.
continue does not leave the loop. It skips the rest of the current pass and goes back to the condition (for while) or to the step and then the condition (for for).
break leaves the loop
This program prints 1, 2, 3 and then stops. When n is 3, break jumps out. 4 and 5 never print, even though the while condition would have allowed them.
Example
let n: number = 1;
while (n <= 5) {
console.log(n);
if (n === 3) {
break;
}
n = n + 1;
}
console.log("after the loop");Compile in /typescript/try. The line after the loop still runs.break ends the loop, not the whole program.
continue skips this iteration
This loop prints the odd numbers from 1 to 5. When n is even, continue jumps to the next pass. The console.log below it does not run for those values.
Example
for (let n: number = 1; n <= 5; n = n + 1) {
if (n % 2 === 0) {
continue;
}
console.log(n);
}% is remainder. Even numbers have remainder 0 when divided by 2, so they are skipped.
continue and while
In a for loop the step still runs after continue. In a while loop there is no hidden step. If the update is below continue, that update never happens and you can loop forever.
Example
let n: number = 0;
while (n < 5) {
n = n + 1;
if (n === 3) {
continue;
}
console.log(n);
}Increment n before continue in a while loop. Put the update after continue and n === 3 never changes.
break in switch is different
You already used break inside switch to stop fall-through. Same keyword, different job: it leaves the switch, not a loop. A break inside a switch that sits inside a loop does not end the loop. It only ends the switch.
continue is not used with switch. It only makes sense in loops.
When to use which
| Keyword | Effect | Typical use |
|---|---|---|
break | Leave the loop now | Found a match, stop searching |
continue | Skip the rest of this pass | Ignore one value, keep looping |
Prefer a clear condition when it reads well: while (n <= 5 && !found) can replace a break. Use break when the stop is in the middle of the body and rewriting the condition would be messier.
Nested loops
break and continue apply to the innermost loop that contains them. Breaking an inner loop does not leave the outer one. If you need to stop both, set a flag in the inner loop and test it in the outer, or put the work in a function and return.
Next: arrays — a list of values, indexed from 0, which for walks naturally.