How to break the forEach loop in JavaScript?

To break the forEach loop in JavaScript, set a local flag variable, then always return if the variable is set.

Here's how you do it:

const array = [ 1, 2, 3, 4, 5 ];

let breakForEach = false;

// prints 1, 2, 3, but not 4, 5
array.forEach(item => {
  if (breakForEach) {
    return;
  }

  console.log(item);

  if (item === 3) {
    breakForEach = true;
  }
});

Unfortunately, there is no built-in, elegant way to do it in JavaScript.