Code example contains solutions for JavaScript forEach break. Using given solutions you can exit from loop when certain condition satisfy.

Note that break; statement not work for forEach loop to break loop execution. There are alternative possible solutions to break forEach loop in JavaScript.

Given solutions will also work for JavaScript inner forEach loop. You can use “for loop” and “throw exception” solution at any level of loop.

If you facing “jump target cannot cross function boundary” or “Uncaught SyntaxError: Illegal break statement” like error, when using break; statement. Following solutions helps to solve fix issues due to break statement usage in forEach loop.

#1 Use for loop

Use for loop instead of forEach. for allow use of break; statement. You can use JavaScript for or for/in or for/of loop to use break; statement.

var categories = [
    {name:'category-1'},
    {name:'category-2'},
    {name:'category-3'}
];

for (i = 0; i < categories.length; i++) {
    if (categories[i].name == 'category-2'){
        break;
    }
    
    console.log(categories[i].name);
};

#2 throw Exception

JavaScript throw Exception is also option to stop execution in forEach loop. Here you need to write your code in try/catch block.

When you want to stop loop, you need to throw Exception and catch it, so, whole JavaScript process not break. In catch block also confirm catched exception is your custom exception and throw back, if exception is other than your break exception.

var categories = [
    {name:'category-1'},
    {name:'category-2'},
    {name:'category-3'}
];

try{
    for (i = 0; i < categories.length; i++) {
        if (categories[i].name == 'category-2'){
            throw 'break';
        }
        
        console.log(categories[i].name);
    };
} catch(e) {
    if (e !== 'break') {
        throw e;
    }
}

Above given are alternative JavaScript forEach break solutions. You can try it if you want to break loop when certain criteria match. If you have other solutions, you can share it here using your comment. It will definitely useful for other users.