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
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

  • By
    Do / Undo Functionality with MooTools

    We all know that do/undo functionality is a God send for word processing apps. I've used those terms so often that I think of JavaScript actions in terms of "do" an "undo." I've put together a proof of concept Do/Undo class with MooTools. The MooTools...

  • By
    RealTime Stock Quotes with MooTools Request.Stocks and YQL

    It goes without saying but MooTools' inheritance pattern allows for creation of small, simple classes that possess immense power.  One example of that power is a class that inherits from Request, Request.JSON, and Request.JSONP:  Request.Stocks.  Created by Enrique Erne, this great MooTools class acts as...

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!