JavaScript by Patrik

Modify the array length

The forEach() function respects changes to the array's length property. So you can force forEach() to break out of the loop early by overwriting the array's length property as shown below.

const myNums = [1, 2, 3, 4, 5];
myNums.forEach((v, index, arr) => {
  console.log(v);
  if (val > 3) {
    arr.length = index + 1; // Behaves like `break`
  }
}

While this approach works, it also mutates the array! If you change the array's length, you effectively truncate the array: subsequent operations, like for/of or JSON.stringify() will only go through the shortened version of the array. Using this approach to break out of a forEach() loop is not recommended.

Comments

Leave a Comment

All fields are required. Your email address will not be published.