Break a forEach Loop with JavaScript

By  on  

I've written a number of blog posts about JavaScript tricks: Promise tricks, type conversion tricks, spread tricks, and a host of other JavaScript tricks. I recently ran into another JavaScript trick that blew my mind: how to break a forEach loop, shared by Andrea Giammarchi!

To break the forEach loop at any point, you can truncate the array's length:

const myArray = [1, 2, 3];
myArray.forEach(item => {
  // ... do some stuff
  if(someConditionIsMet) {
    // Break out of the loop by truncating array
    myArray.length = 0;
  }
})

By setting the array's length to 0, you empty out the array and immediately halt the forEach. Of course, emptying out the array loses its original data, so you may want to create a new array ([...myArray].forEach) before this operation.

Another way of accomplishing the task would be throwing an exception instead:

// https://stackoverflow.com/questions/2641347/short-circuit-array-foreach-like-calling-break
let BreakException = {};

try {
  [1, 2, 3].forEach(function(el) {
    console.log(el);
    if (el === 2) throw BreakException;
  });
} catch (e) {
  if (e !== BreakException) throw e;
}

And of course, there will likely be a better way to get what you want without needing this trick, like using .find or .some, but not every trick needs to be a best practice!

Recent Features

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

Incredible Demos

  • By
    Chris Coyier: Some Amazing Work on CodePen III

    I'm back! David asked me to rope up some of my favorite stuff on CodePen again, which I both love doing, and wince at the thought of having to pick so few favorites. I like a ton of stuff on...

  • By
    9 Incredible CodePen Demos

    CodePen is a treasure trove of incredible demos harnessing the power of client side languages.   The client side is always limited by what browsers provide us but the creativity and cleverness of developers always pushes the boundaries of what we think the front end can do.  Thanks to CSS...

Discussion

  1. àlfons

    about the proposed [...myArray].forEach

    if you define myArray.length to zero later, it erases the array anyway

    • The third argument to forEach is the array itself, so you could use that.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!