How to Break Out of Loops in TypeScript?

In this tutorial, I will explain how to exit or break out of loops in TypeScript. The break statement in TypeScript allows you to terminate a loop and pass program control to the next statement after the loop. It helps exit the loop midway before the loop condition becomes false.

There are different methods to break out of loops in TypeScript. Let me show you a few methods with examples.

Using the break Statement

The break statement is used to break out of loops like for, while, and do...while loops. Here’s an example:

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

In this example, the loop will print numbers from 0 to 4 and then exit when i becomes 5 due to the break statement.

Here is the exact output in the screenshot below:

Break Out of Loops in TypeScript

Check out How to Break Out of a forEach Loop in TypeScript?

Breaking Out of Nested Loops

When dealing with nested loops in TypeScript, the break statement only exits the innermost loop. For example:

const cities = ['New York', 'Los Angeles', 'Chicago'];
const states = ['NY', 'CA', 'IL'];

for (const state of states) {
  for (const city of cities) {
    console.log(`${city}, ${state}`);
    if (city === 'Los Angeles') {
      break;
    }
  }
}

In this case, the inner loop will break when the city is ‘Los Angeles’, but the outer loop will continue iterating through the remaining states.

Here is the exact output in the screenshot below:

TypeScript Break Out of Loops

Read TypeScript forEach Loop with Index

Break Out of forEach Loops in TypeScript

The break statement cannot be used directly with forEach loops in TypeScript. Instead, you can use Array.every() or Array.some() to achieve similar behavior. Here’s an example using Array.every():

const numbers = [1, 2, 3, 4, 5];

numbers.every((num) => {
  console.log(num);
  return num !== 3;
});

In this example, the loop will print numbers 1, 2, and 3, and then exit when the condition num !== 3 becomes false.

Here is the exact output in the screenshot below:

Break Out of forEach Loops in TypeScript

Conclusion

We need to break out of loops in TypeScript for controlling the flow of your program. The break statement is commonly used with for, while, and do...while loops, while Array.every() or Array.some() can be used with forEach loops. In this tutorial, I explained how to break out of loops in TypeScript with some examples.

You may also like: