Break statement in Typescript

The TypeScript break statement breaks out or exits the current loop, switch statement, or a labeled block. It is a very useful statement, which helps us to exit the loop midway when a certain condition occurs. The break transfers the control to the very next statement after the loop, switch, or a labeled block.

Syntax

The Syntax of the break statement is as follows.

Where the label is optional. Use it to correctly identify which loop to exit in the case of a nested loop. It is a must if you want to exit out of a labeled block

Break out of a for Loop

In the following example, the if statement breaks out when the value of i is 6. The values 6 to 10 are never printed as the for loop terminates after the break.

Break out of a while Loop

Similarly, we break out here when the value of num2 is 3.

Break out of a switch

The Switch statements use the Break to break out of the switch. Otherwise, the execution of the switch continues to the next case clause.

Break out of a nested Loop

In the following code, we have a nested for loop.

The break statement here exits the inner loop and not from the outer loop.

To break out of the outer loop, we need to use the labels.

The Typescript allows us to prefix a statement with a label. The break can make use of it.

In the following example, we prefix the outer loop with outerloop label. And inner loop with innerloop label.

In the break statement, we use the outerloop, which will make the break to exit from the outer loop

Break from a labeled block

In the following example, we have two blocks outer & inner. The statement break outer; will exits from the outer block.

The following results in a syntax error. The break statement can only exit out of a block, loop, or a switch, which it is part of.

In the following example, the break cannot exit blk2, because it is not part of it. It can only exit from the blk1. Hence the following code results in an error.

References

  1. Break
  2. Label
  3. Continue

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top