Fix - Illegal break statement Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Fix - Illegal break statement Error in JavaScript #

The "Illegal break statement" error occurs when we try to use a break statement outside of a for loop, or use a break statement inside of a function in the for loop.

illegal break statement

Here's an example of when the error occurs.

index.js
let arr = ['a', 'b', 'c']; arr.forEach(element => { if (element === 'b') { break // 👉️ Uncaught SyntaxError: Illegal break statement } console.log('test'); });

The code snippet above causes the error because we try to use the break statement in a function.

To solve the "Illegal break statement" error in JavaScript, only use break statements in loop that support the break keyword. You can 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.js
let 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, try using a for ... of loop instead. You can use the break keyword in a for ... of loop.

index.js
let arr = ['a', 'b', 'c']; for (const element of arr) { if (element === 'b') { break; } console.log(element) // 👉️ a }
Use the search field on my Home Page to filter through my more than 1,000 articles.