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 Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

  • By
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

Incredible Demos

  • By
    Sexy Opacity Animation with MooTools or jQuery

    A big part of the sexiness that is Apple software is Apple's use of opacity. Like seemingly every other Apple user interface technique, it needs to be ported to the web (</fanboy>). I've put together an example of a sexy opacity animation technique...

  • By
    FileReader API

    As broadband speed continues to get faster, the web continues to be more media-centric.  Sometimes that can be good (Netflix, other streaming services), sometimes that can be bad (wanting to read a news article but it has an accompanying useless video with it).  And every social service does...

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!