Skip to main content

Break and Continue

As a beginner learning TypeScript, understanding control flow is essential. In this tutorial, we'll discuss two crucial control flow statements, 'Break' and 'Continue', to help you master how to control the execution of your code effectively.

Break and Continue in TypeScript

Break Statement

In TypeScript, the break statement is used to terminate a loop, switch, or together with a labeled statement.

When a break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop.

Here's a basic example:

for(let i = 0; i < 10; i++) {
if(i == 5) {
break;
}
console.log(i);
}

In this example, the loop will break once i equals 5, and we will only see the numbers 0 to 4 in the console.

Continue Statement

The continue statement is used to skip the rest of the code inside the current iteration of the loop and immediately move on to the next iteration.

Here's a simple example of how the continue statement works:

for(let i = 0; i < 10; i++) {
if(i == 5) {
continue;
}
console.log(i);
}

In this example, when i equals 5, the continue statement will skip the remaining code in the loop for that iteration (which is the console.log(i) statement) and move on to the next iteration. So, we won't see the number 5 in the console output.

Using Break and Continue in While Loops

Just like for loops, break and continue statements can also be used in while loops. Here's an example:

let i = 0;
while(i < 10) {
if(i == 5) {
i++;
continue;
}
console.log(i);
i++;
}

In this example, when i equals 5, the continue statement will skip the console.log(i) statement, and 5 will not be printed in the console.

Conclusion

The break and continue statements provide you with more control over your code's flow in TypeScript. They can help you optimize your code, skip unnecessary iterations, or exit a loop when a specific condition is met. Understanding how and when to use these statements can be a powerful tool in your TypeScript toolkit. However, it's crucial to use them judiciously, as improper use can lead to code that is difficult to read and debug.