Borislav Hadzhiev
Mon Mar 14 2022·2 min read
Photo by Cristina Munteanu
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.
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.
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.
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:
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.
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.
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.
function example() { return; }