How to break out of forEach loop in JavaScript

Sep 08, 2023#javascript#how-to

The forEach loop in JavaScript is designed to iterate over the elements of an array and apply a provided function to each element.

forEach(callbackFn)
forEach(callbackFn, thisArg)

Unlike some other looping constructs, the forEach loop does not have built-in mechanisms for breaking out of the loop prematurely. It will continue to iterate over all elements in the array until it has processed all of them. Using break statement will raise SyntaxError.

let numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => {
  if (number === 4) {
    break; // ❌ SyntaxError: Illegal break statement
  }
  console.log(number);
});

You may want to use other types of loops that support breaking like for or for...of. These loops are more flexible and intuitive than using with forEach. If you insist in using forEach loop and want to break early, here some workarounds:

  1. Throw an exception to break out of the forEach loop. This is not a recommended practice because it involves using exceptions for control flow, which can make your code less readable and maintainable.
let numbers = [1, 2, 3, 4, 5];

try {
  numbers.forEach(number => {
    if (number === 4) {
      throw new Error("Number is 4");
    }
    console.log(number);
  });
} catch (error) {
  console.error(error.message);
}

// The output will be:
// 1
// 2
// 3
// Number is 4
  1. Filter out the values you want to skip before using forEach. This way, you avoid unnecessary iterations and can control when to stop.
let numbers = [1, 2, 3, 4, 5];

numbers
  .filter(number => number != 4)
  .forEach(number => {
    console.log(number)
  });

// The output will be:
// 1
// 2
// 3
// 5
  1. You can declare a variable outside the forEach loop and set it to true or false depending on your condition. Then, inside the forEach function, you can check the variable and return immediately if it is true. This will not break out of the loop, but it will skip the remaining iterations.
let numbers = [1, 2, 3, 4, 5];
let stop = false;

numbers.forEach(number => {
  if (stop) {
    return; // Skip the remaining iterations
  }
  if (number === 4) {
    stop = true; // Stop the loop after this iteration
  }
  console.log(number);
});

// The output will be:
// 1
// 2
// 3
// 4
  1. Modify the array length inside the forEach function. This is a hacky and not recommended way, but it works. You can access the array and its length property inside the forEach function, and overwrite it with a smaller value when you want to stop the loop. This will cause forEach to terminate early, but it will also mutate the original array and may cause unexpected side effects.
let numbers = [1, 2, 3, 4, 5];

numbers.forEach((number, index, array) => {
  if (number === 4) {
    array.length = index + 1; // Modify the array length to stop the loop
  }
  console.log(number);
});

// The output will be:
// 1
// 2
// 3
// 4

// The original array will be changed to:
// [1, 2, 3, 4]