šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Fixing the Jump target cannot cross function boundary in Javascript

While working on some js code that contained named labels and break statements I ended up with the following error:

Jump target cannot cross function boundary

The code that I was trying to run was something similar to the one below:

const cars = ['Audi', 'BMW', 'Honda', 'Ford', 'Doge']

// ā›”ļø using break in forEach with cause the
// "Jump target cannot cross function boundary" error
cars.forEach(carName => {
    console.log(carName)
    if(carName === 'BMW') {
        break
    }
})

The reason why this happened is because array forEach() is a function, and it seems that you can't use break to exit a function:

// ā›”ļø this will also cause the  
// "Jump target cannot cross function boundary" error
function myFunc(x) {
    if(x === true) {
        break
    }
}

A quick fix for this can be to use a for ... of, or just a plain old for statement:

// šŸ‘ Solution: use the return statement
for(let carName of cars) {
    console.log(carName)
    if(carName === 'BMW') {
        break
    }
}

The full code is on my Github and the running example is here.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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