How to break out of a for loop in JavaScript
By Flavio Copes
Learn how to break out of a for or for..of loop in JavaScript with the break statement, and why you cannot break out of a forEach loop the same way.
You break out of a for loop in JavaScript using the break statement. The loop stops immediately, and execution continues with the first line after it.
Say you have a for loop:
const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
console.log(`${i} ${list[i]}`)
}
If you want to break at some point, say when you reach the element b, you can use the break statement:
const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
console.log(`${i} ${list[i]}`)
if (list[i] === 'b') {
break
}
}
This prints 0 a and 1 b, then stops. The c element is never reached.
You can use break also to break out of a for..of loop:
const list = ['a', 'b', 'c']
for (const value of list) {
console.log(value)
if (value === 'b') {
break
}
}
The same statement works in while and do..while loops too. It’s the standard way to stop a loop early, typically once you found the thing you were searching for and there’s no reason to keep going.
break vs continue
Don’t confuse the two. break ends the whole loop. continue skips the rest of the current iteration and jumps to the next one:
const list = ['a', 'b', 'c']
for (const value of list) {
if (value === 'b') {
continue
}
console.log(value)
}
//a
//c
You can’t break out of forEach
Note: there is no way to break out of a
forEachloop, so (if you need to) use eitherfororfor..of.
This is a classic pitfall. You write break inside the callback, and you get:
list.forEach((value) => {
if (value === 'b') {
break //SyntaxError: Illegal break statement
}
})
The reason is that the callback is a regular function, and break only works directly inside a loop. forEach always calls the function once per element, no matter what.
The fix is to switch to for..of, which supports break and reads just as well.
Breaking out of nested loops
break only exits the innermost loop it lives in. To exit an outer loop from within an inner one, add a label and break to it:
outer: for (const row of grid) {
for (const cell of row) {
if (cell === 'x') {
break outer
}
}
}
Without the label, only the inner loop stops, and the outer one moves on to the next row.
Related posts about js: