break
Immediately ends a loop or a switch statement and moves on to the code right after it.
Example
#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)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
#break
break labelMore examples
#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)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)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,breakis a syntax error. Choosefor...of, or methods that end the work themselves:find(),some(), andevery(). - Use labels sparingly. It’s often more readable to pull nested loops out into a function and exit them with
return.
Related entries
#- continueSkips the rest of the current loop turn and moves straight to the next one.
- forA loop with a counter: initialization, condition, and step. Repeats a block of code while the condition is true.
- whileRepeats a block of code while the condition is true. The condition is checked before every turn.
- switchCompares a value against a list of case labels and runs the code from the first match.
- Array.prototype.find()Returns the first element that matches a condition, or undefined.
- Array.prototype.some()Checks whether at least one element matches a condition.
Spotted a mistake or missing an example? Write to us.