Unsyntactic break Error in JavaScript [Solved]


Borislav Hadzhiev

Last updated: Oct 10, 2021


Photo from Unsplash

Unsyntactic break Error in JavaScript [Solved] #

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

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

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

To solve the "Unsyntactic break" error in JavaScript:

  • Only use break statements in loops that support the break keyword.
  • 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.
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.

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

Further Reading #

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.