Last Updated: July 31, 2019
· afshinm

Don't use Array.forEach, use for() instead

Array.ForEach is about 95% slower than for() in for each for Arrays in JavaScript.

So, don't use:

arr.forEach(function (item) {


for (var i = 0, len = arr.length; i < len; i++) {

See this performance test online: http://jsperf.com/fast-array-foreach

57 Responses
Add your response


In first example you can write something like this:


It's really useful.
In some cases you'll realy need to use forEach method. For example, if you need a closure for your loop.

  var attribute = element.getAttribute('data-attr');
  element.onclick = function(){
over 1 year ago ·

@avenger7x Sure, yes. I forgot to mention when we need to use forEach but in some cases that I saw in applications, it uses incorrectly and only because it's easy-to-use.

over 1 year ago ·

for loops are really annoying when you're trying to build something complex, maintainability becomes harder, I think that there is a third solution http://mlb.tl/LIFL which is faster than forEach and still keeps a nice FP & OO coding-style.

Otherwise I agree that for small scripts, a good old for loop can be accurate.

over 1 year ago ·

@mlb Hey Thanks, good alternative solution.

over 1 year ago ·

This is faster:
var l=this.length;
for(var i=0;i<l;i++)a(this[i],i)

over 1 year ago ·

One other reason not to use Array.forEach is that it is not supported by IE8.

over 1 year ago ·

lol. Since when IE8 is supposed to rule our choices ?
The fact that IE8 doesn't support Array.forEach really means this bowser is deep shit, that's all ! ;)

over 1 year ago ·

Micro premature optimization is the root of so many evils. The rule is don't use it in a tight loop. Anywhere else, it will never matter. DOM maintenance is where you should optimize.

over 1 year ago ·

One other reason to use Array.forEach is that it is not supported by IE8. ;-)

over 1 year ago ·

JSPerf is a double-edged sword, you really need to start thinking about what it does and how it can return confusing results. Furthermore, 95% slower is practically NOTHING in terms of JS performances. What you need to focus on is Draw counts (if you are working the canvas) or plain DOM updates. Check out this great speak on micro-optimizations: https://www.youtube.com/watch?v=65-RbBwZQdU

over 1 year ago ·

@william_malo, your test is misleading. Your vanilla javascript for loop was not actually calling the function, but merely running the guts of the function within the loop. Here is a more accurate test: http://jsperf.com/sdngjkn/19

over 1 year ago ·

In your test and in ntg's, forEach was the fastest in Firefox 38 on 64-bit Linux (Slackware).

over 1 year ago ·

for() loop runs in sync mode, it is too bad for a js application, if you are programming a js app, you'd better use Array.forEach, it runs in async mode, else you won'd go far.

over 1 year ago ·

There is a difference between for and forEach. for will local reassign variable for every run, while forEach will create new variable. Example:

var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
  var element = links[i];
  element.addEventListener('click', function () {
    alert(element.innerText); // you think it will be element you clicked on? It will be last element in array
over 1 year ago ·

The main reason for using for loops over Array.forEach is that you cannot break the latter. Other than that, I prefer the Array.forEach semantics. If performance degradation is really noticeable I will take into account your suggestion. Thank you.

over 1 year ago ·

Note that this is only for ES5 in a browser. If you've got ES6 then you'll want to use for ( X of arr ) { ... }.

over 1 year ago ·

Don't forget to weigh performance against legibility/maintainability. As juanmendes said, premature optimization can yield problems.

over 1 year ago ·

Personal opinion, here, but I think there is a larger issue being overlooked here.

The purpose of either for() or .forEach() is presumably to actually do something with each of the array elements. Simply comparing the two method's speed, divorced from actually doing anything inside their loops is a rather meaningless comparison. The work being done inside the loop of each method is going to dwarf the execution speed of the looping mechanism itself, almost to the point of irrelevance.

By the time you add a simple database lookup, and a printf(), 99.9% of the time is going to be spent on the work, and 0.1% of the time is consumed by the actual looping mechanism overhead.

If you had a million array elements to iterate, and nothing more than "i++;" inside the loop, then yeah, maybe the benefits of for() over .forEach() might be worth considering. But this is rarely the case.

over 1 year ago ·

Or use lodash's forEach implementation which is about as performant as the plain for loop.

over 1 year ago ·

Thanks for sharing a useful information.

over 1 year ago ·

This is a terrible tip and I'll explain why.

  • Javascript has functions as a first class citizen. each/forEach is only slower because it creates a lexical scope around each loop iteration. In practice this is usually what you want.
  • 9/10 times you really want .map. You're probably looping in order to transform data.
  • loops favor side effects over pure functions. this means reaching into other scopes, and unpredictability. .map and functional approaches are objectively easier to test
  • if you have code where you are iterating so much that a for loop performance over map is so significant, you probably need to download lodash anyways.
  • if you really, really really must loop. (note: you probably don't) do NOT evaluate length in the iterator!! that gets called every time!
  • and if you REALLY must loop a while with a -- decrementor is actually even faster. Following the guidelines of asm.js are even better than that..Again, you probably do not need this in everyday practice, the tradeoof for testability and readability is not usually worth it.

Don't use loops. Don't use each. Use pure functions with no side effects. Map, filter, reduce.

over 1 year ago ·

In My tests performance for forEach, is similar to (for(;;) loops, in smaller arrays, forEach is even faster, (for of) is the slowest unfortunately

over 1 year ago ·

I would use Array.forEach over for() any day.

over 1 year ago ·

@the-simian, caching array.length outside of the iterator and reverse/decrementing loops are no longer necessarily faster. Reasonably modern JavaScript engines automatically optimise established patterns, such as forward loops and evaluating length - writing them in an "optimised way" prematurely simply adds confusion.

over 1 year ago ·

I also make a compare test with native loop, native foreach, lodash foreach and underscoure foreach.

over 1 year ago ·

for loops are really annoying when you're trying to build something complex, maintainability becomes harder, I think that there is a third solution http://gastrichealthtablet.org http://triflexcapsule.com

over 1 year ago ·

Premature optimization!!!

over 1 year ago ·


over 1 year ago ·

Don't use for(), because it is ugly

over 1 year ago ·

thank you for allowing us to share information.
hopefully we are all in the given smoothness

over 1 year ago ·

I think the description here is incorrect. It is not 95% slower. That would mean it runs 1/20 of the speed of the other. It is "...95% as fast..." or "...5% slower..." (which is the terminology used in the test link).

over 1 year ago ·

This appears to no longer be true. The jsperf link showed for/forEach take about the same time in FF51.

over 1 year ago ·

This is valid only if you experience real performance problems. If not, it is premature optimisation at its best (or worst :) ). Main question here - what is more expensive to the company: code, running some miliseconds or microseconds slower, or the developers, spending minutes => hours => days reading it, trying to figure what all these loops all over the project actually do. :) Remember, we spend more time reading code, than writing it.
Actually, the example makes me want rewrite it to use map or reduce, instead of forEach (depending of what someFn does), but that's another story.

over 1 year ago ·

How about WHILE () {}??

over 1 year ago ·

@avenger7x you could still have a closure with a for loop if you make the function outside the for loop

over 1 year ago ·

@the-simian I agree with you so much!

over 1 year ago ·

Do yourself a favor as a coder and DO NOT follow this "tip". Instead, read the-simian's comment.
Rule #1 in coding: do not attempt premature optimization, favor code clarity and simplicity.

over 1 year ago ·

joanllenas, you don't need a break in .forEach(). Because you use it as the name says — when you want your function to be executed against each element of array. If you want it to be executed only again some of them, there's a method called exactly like that — .some() (see Array.prototype.some).

over 1 year ago ·

Thank you for this share

over 1 year ago ·

One will step through each iteration synchronously; the other will run each function as separate in the event queue:

For example:
for (let i = 0; i < arr.length; i++) { setTimeout(() => { console.log(arr[i]); }, 100); }
will give a different result than
arr.forEach((ele) => { setTimeout(() => { console.log(ele); }; };

over 1 year ago ·

If considering modern browsers (with full ES6 support) , my favorite is "for of" loop. Like
for(let i of j){
//do something

over 1 year ago ·

What about this test? What is the difference I wonder.


over 1 year ago ·

you can't use for loop in async javascript

over 1 year ago ·

Great tip. I love simplicity and nothing beats it like native, well known language constructs. But, if what dillon-bostwick claims is true (all evidence I see is to the contrary), then the foreach does have that in its favor.

over 1 year ago ·

The only reason a for loop is faster is that the browsers have optimized it. Once we start using methods like forEach, map, reduce and filter, the browsers will optimize for those as well. Plus, for loops are not asynchronous.

over 1 year ago ·

Damn, this is just another confirmation of why I recently switched to Firefox...

Array.forEach - 48,912
For - 504,695

Array.forEach - 1,024,928
For - 1,127,704

But of course, one should implement according to what the most popular browser demands...

over 1 year ago ·

Another way is to use closure.
var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { (function(element) { element.addEventListener('click', function(ev) { ev.preventDefault(); alert(element.innerText); }); })(links[i]); }

over 1 year ago ·

this is rarely the case.

over 1 year ago ·

this code is bullshit see the output:
see the usage:

function addtext(text,elementobj)
elementobj.innerHTML = elementobj.innerHTML.replace("<span class=\"cursor\"></span>","") + text + "<span class=\"cursor\"></span>";

function logcharbychar(text,elementobj,chartime=20)
var arr = Array.from(text);
for (var i = 0, len = arr.length; i < len; i++) {

logcharbychar("foo bar",document.getElementById("icode"),1000);


10 months ago ·

You’ll notice one of the overarching concepts of all these three methods is that they all take the “functional route”, where they don’t necessarily require the manual creation of additional state. It is possible to introduce side effects within these methods, however, they don’t primarily rely on side effects to function. In other words, you’ll see that Array.prototype.forEach primarly relies on side effects. It never returns a value other than undefined unless you explicity force it to.

9 months ago ·

Like I've said before, loops are blocking (synchronous), yes they seem fast because browser companies optimize code that people are using, since most newbie devs use for loops and while loops, they are the ones that will get optimized. For asynchronous programming, I would suggest using a functional approach like using higher order functions like map, reduce, filter, even forEach. The the first secret to mastering asynchronous programming: programming without loops. JavaScript's loops can only run synchronously, and cannot be used to repeat asynchronous functions. As a result, in order to master asynchronous programming we must first master programming without loops. So please, stop using for loops because some perf you or someone else ran is faster than option x. Sure use loops if you're not writing asynchronous applications but in JavaScript land (and Node land) , where we only have a single thread, writing non-blocking code is key.

9 months ago ·

As @tonyb67 points out, many programmers seem confused (including myself) about JS and thinking in an asynchronous vs synchronous way. It leads to many unexpected results in large code bases especially when mixed. I rarely see this topic covered thoroughly.

6 months ago ·

// shortest and fastest loop, when no index < length is 'undefined'
var x, i = 0
while (x = arr[i++]) {

5 months ago ·

I need to move variables from a Google sheet and arrange them in an arrangement to distribute them in different cells of another spreadsheet, I do not know what function is needed for this case ...

2 months ago ·

Many thanks, I tried using your way and the results are surprising here: https://mobdroplus.com/

22 days ago ·