break

Immediately ends a loop or a switch statement and moves on to the code right after it.

On this page

Example

#
JavaScript
const answers = [4, 7, 12, 3, 15]
let firstBig

for (const answer of answers) {
  if (answer > 10) {
    firstBig = answer
    break
  }
  console.log('Checking', answer)
}

console.log('Found', firstBig)
Console
Checking 4
Checking 7
Found 12

Definition and usage

#

The break statement stops the nearest loop (for, while, do...while, for...of, for...in) or switch. The program moves to the first statement after the ended block, and the remaining turns are skipped.

A typical use is searching: once you find what you’re looking for, there’s no point checking further. Inside switch, break ends the current case so execution doesn’t fall through to the next one.

In nested loops, break only stops the inner loop. To exit several at once, label the outer loop, e.g. outer:, and write break outer. break doesn’t work inside forEach() callbacks, since those are separate functions.

Syntax

#
Syntax
break
break label

More examples

#
Exiting nested loops with a label
JavaScript
const map = [
  ['.', '.', '.'],
  ['.', '.', 'X'],
  ['.', 'X', '.']
]
let found = null

outer: for (let row = 0; row < map.length; row++) {
  for (let col = 0; col < map[row].length; col++) {
    if (map[row][col] === 'X') {
      found = { row, col }
      break outer
    }
  }
}

console.log(found)
Console
{ row: 1, col: 2 }
break in a while (true) loop
JavaScript
const bonuses = [5, 10, 20, 50]
let total = 0

while (true) {
  const bonus = bonuses.shift()
  if (bonus === undefined || total + bonus > 30) break
  total += bonus
}

console.log(total)
Console
15

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • In forEach(), map(), and other callbacks, break is a syntax error. Choose for...of, or methods that end the work themselves: find(), some(), and every().
  • Use labels sparingly. It’s often more readable to pull nested loops out into a function and exit them with return.

Related entries

#

Spotted a mistake or missing an example? Write to us.