How to break a forEach() loop in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 14, 2022

banner

Photo from Unsplash

Break a forEach() loop in TypeScript #

To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection.

index.ts
const arr: string[] = ['one', 'two', 'three']; const BreakError = {}; try { arr.forEach((element) => { if (element === 'two') { throw BreakError; } console.log(element); // 👉️ one }); } catch (err) { if (err !== BreakError) throw err; }

We are not able to use the break statement outside of a loop - e.g. in a forEach() method, so we had to wrap the forEach method in a try/catch block.

We basically throw an error to break out of the forEach() method, in the same way we would break out of a loop with a break statement.

The error is caught in the catch block, so our application keeps running without any issues.

In our catch block, we check if the caught error is not equal to the BreakError we threw and rethrow it if it isn't. This helps us avoid silencing any real errors in the body of the forEach() method.

If you try to break out of a forEach() method using the break statement, you would get an error.

index.ts
const arr: string[] = ['one', 'two', 'three']; arr.forEach((element) => { if (element === 'two') { // ⛔️ Error: Jump target cannot // cross function boundary.ts(1107) break; } });

This is because the break statement can only be used to break out of loops, but we are trying to use the keyword in a function.

If you only want to break out of a single iteration in a forEach() method, you would use a return statement.

index.ts
const arr: string[] = ['one', 'two', 'three']; arr.forEach((element) => { if (element === 'two') { return; } console.log(element); // 👉️ one, three });
The example above only skips the second iteration, as using a return statement with forEach() is the same as using continue in a loop - it terminates only the current iteration and continues with the next iteration.

Note that we can use the break statement in the following scenarios:

  • basic for loops
  • for ... of loops
  • for ... in loops
  • while loops
  • switch statements

This means that you could potentially use a for...of loop instead of the forEach() method and use a break statement to exit.

index.ts
const arr: string[] = ['one', 'two', 'three']; for (const element of arr) { if (element === 'two') { break; } console.log(element); // 👉️ "one" }

The for...of loop iterates over the array in the same way as forEach(), but enables us to use a break statement.

If you need access to the current index when iterating, you could use a basic for loop.

index.ts
const arr: string[] = ['one', 'two', 'three']; for (let i = 0; i < arr.length; i++) { if (arr[i] === 'two') { break; } console.log(arr[i]); // 👉️ "one" }

The syntax for a basic loop is a bit verbose, but enables us to use the break statement and gives us access to the index of the current iteration.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.