Jump target cannot cross function boundary in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 14, 2022

banner

Photo from Unsplash

Jump target cannot cross function boundary in TypeScript #

The "Jump target cannot cross function boundary" error occurs when we try to use a break statement outside of a for loop, e.g. in forEach() or a function. To solve the error only use a break statement in for loops and exit forEach() functions by throwing and catching an error.

Here are two examples of how the error occurs.

index.ts
const arr = ['a', 'b', 'c']; arr.forEach((value) => { if (value === 'b') { // ⛔️ Error: Jump target cannot cross function boundary.ts(1107) break; } console.log(value); }); function example() { // ⛔️ Error: Jump target cannot cross function boundary.ts(1107) break; // 👉️ use return (not break) }

The break statement is used to terminate the current loop.

The error in the examples above occurred because we used the break keyword outside of a loop.

To solve the error if using the forEach method, throw an error in a try/catch block to break out of the loop if you're in a function and can't use the break statement.

index.ts
const arr = ['a', 'b', 'c']; const BreakError = {}; try { arr.forEach((element) => { if (element === 'b') { throw BreakError; } console.log(element); // 👉️ a }); } catch (err) { if (err !== BreakError) throw err; }

In the code snippet, we throw an error to break out of the iteration. We can't use the break keyword inside a function, so we wrap the function in a try/catch block and throw an error to exit when we need to.

We can use the break statement in the following scenarios:

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

If you're using a forEach loop and trying to use a break statement, you can try using a for ... of loop instead. You can use the break keyword in a for ... of loop.

index.js
const arr = ['a', 'b', 'c']; for (const element of arr) { if (element === 'b') { break; } console.log(element); // 👉️ a }

The error often occurs when we try to use a break statement to exit a function.

index.ts
function example() { // ⛔️ Error: Jump target cannot cross function boundary.ts(1107) break; // 👉️ use return (not break) }

You can use the return statement to exit a function.

index.ts
function example() { return; }

Conclusion #

The "Jump target cannot cross function boundary" error occurs when we try to use a break statement outside of a for loop, e.g. in forEach() or a function. To solve the error only use a break statement in for loops and exit forEach() functions by throwing and catching an error.

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.