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

Imagine you have a for loop like this:

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:

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:

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