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
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

Incredible Demos

  • By
    jQuery UI DatePicker:  Disable Specified Days

    One project I'm currently working on requires jQuery. The project also features a datepicker for requesting a visit to their location. jQuery UI's DatePicker plugin was the natural choice and it does a really nice job. One challenge I encountered was the...

  • By
    Drag and Drop MooTools File Uploads

    Honesty hour confession:  file uploading within the web browser sucks.  It just does.  Like the ugly SELECT element, the file input is almost unstylable and looks different on different platforms.  Add to those criticism the fact that we're all used to drag and drop operations...

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!