Solve - Unsyntactic break Error in JavaScript


Borislav Hadzhiev

Sun Oct 10 20212 min read

Solving - Unsyntactic break Error in JavaScript #

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 loop 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 }

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee