How to break out of a for loop in JavaScript
Find out the ways you can use to break out of a for or for..of loop in JavaScript
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
}
}
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
}
}
Note: there is no way to break out of a
forEach
loop, so (if you need to) use eitherfor
orfor..of
.
→ Get my JavaScript Beginner's Handbook
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025