/

How to Break Out of a For Loop in JavaScript

How to Break Out of a For Loop in JavaScript

Learn the different methods to break out of a for or for..of loop in JavaScript.

Imagine you have a for loop like this:

1
2
3
4
const list = ['a', 'b', 'c'];
for (let i = 0; i < list.length; i++) {
console.log(`${i} ${list[i]}`);
}

If you want to stop the loop at a specific point, for example, when you reach the element ‘b’, you can use the break statement:

1
2
3
4
5
6
7
const list = ['a', 'b', 'c'];
for (let i = 0; i < list.length; i++) {
console.log(`${i} ${list[i]}`);
if (list[i] === 'b') {
break;
}
}

The break statement can also be used to break out of a for..of loop:

1
2
3
4
5
6
7
8
const list = ['a', 'b', 'c'];

for (const value of list) {
console.log(value);
if (value === 'b') {
break;
}
}

Please note that there is no way to break out of a forEach loop, so if you need to break out of a loop, it is recommended to use either a for loop or for..of loop.

Tags: JavaScript, for loop, break statement, for..of loop