Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Roberto Nickson
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.
Here's an example of when the error occurs.
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.
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 }