What are the ways we can break out of a loop in JavaScript?

By

Learn the ways to break out of a loop in JavaScript using the break keyword in for, for..of and while loops, plus why continue and for..in differ.

~~~

Here is a for loop:

const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {

}

Left alone, this loop runs until the condition i < list.length becomes false. But sometimes you already found what you were looking for, and running the remaining iterations is wasted work.

We can break at any point in time the execution using the break keyword:

const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
  if (list[i] === 'b') break
  console.log(list[i])
}

This prints only a. When the loop reaches the 'b' element, break ends it immediately, and execution continues with the first statement after the loop’s closing brace.

break also works in for..of loops:

const list = ['a', 'b', 'c']
for (const item of list) {
  if (item === 'b') break
  console.log(item)
}

And in while:

const list = ['a', 'b', 'c']
let i = 0
while (i < list.length) {
  if (list[i] === 'b') break
  console.log(list[i])
  i++
}

All three versions print a and stop.

break vs continue

The continue keyword lets us skip one iteration, in the for and for..of and while loops. The loop does end that iteration, and will continue from the next one:

const list = ['a', 'b', 'c']
for (const item of list) {
  if (item === 'b') continue
  console.log(item) //a, then c
}

The difference is scope: break abandons the whole loop, continue abandons only the current iteration.

Breaking out of nested loops

By default break exits only the innermost loop. If you need to escape an outer loop too, give it a label:

outer: for (const row of [[1, 2], [3, 4]]) {
  for (const cell of row) {
    if (cell === 3) break outer
    console.log(cell) //1, 2
  }
}

Labels look unusual and you will rarely need them, but for this specific job nothing else is as clean.

Where break does not work

break and continue work in every loop statement: for, for..of, for..in, and while.

Where break does not work is forEach(). There is no way to stop a forEach once it started — writing break inside the callback is a syntax error, and return only ends the current callback call, acting like continue. If you expect to exit early, my advice is to reach for for..of instead, or use some(), which stops as soon as the callback returns true.

~~~

Related posts about js: