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 @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

Incredible Demos

  • By
    JavaScript Speech Recognition

    Speech recognition software is becoming more and more important; it started (for me) with Siri on iOS, then Amazon's Echo, then my new Apple TV, and so on.  Speech recognition is so useful for not just us tech superstars but for people who either want to work "hands...

  • By
    GitHub-Style Sliding Links

    GitHub seems to change a lot but not really change at all, if that makes any sense; the updates come often but are always fairly small. I spotted one of the most recent updates on the pull request page. Links to long branch...

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!