Last updated: Dec 28, 2022
Reading time·2 min
The "SyntaxError: Illegal break statement" 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 causes the error because we try to use the break
statement in a
function.
You might also encounter the error with a different name:
The "SyntaxError: Unsyntactic break" and "SyntaxError: Illegal break statement"
errors occur for the same reason - using the break
statement outside a for
loop.
forEach()
Only use break
statements in loops 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; }
We threw 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
statement
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.
const arr = ['bobby', 'hadz', '.', 'com']; for (const element of arr) { if (element === 'hadz') { break; } console.log(element); // 👉️ bobby }
for...of
loop instead of forEach()
You don't have access to the index of the current iteration in a for...of
loop
but you are able to use the break
statement in it.
You could also declare an index
variable using the let
keyword and increment
the variable on each iteration of the loop.
const arr = ['bobby', 'hadz', '.', 'com']; let index = 0; for (const element of arr) { console.log(index); if (element === 'hadz') { break; } console.log(element); // 👉️ bobby index += 1; }
We increment the index
variable at the bottom of the for...of
loop to
simulate an index.
To solve the "SyntaxError: Illegal break statement" error in JavaScript, only
use break
statements in loops 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.