Borislav Hadzhiev
Sun Oct 10 2021·2 min read
Photo by Ben Waardenburg
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:
break
statements in loop that support the break keyword.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:
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 }