Last Updated: January 16, 2017
· 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

30 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 ·
0 5p24ii3mi4rr mb4fqfbiecyixurke94fn4bie3aqszi723zdvpqshvhla2x17cqkka62fxg1lpp

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
11 months ago ·
Img 20151108 wa0019

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.

10 months 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 ) { ... }.

10 months ago ·

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

10 months 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.

8 months ago ·

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

7 months ago ·
Gade cosmetics

Thanks for sharing a useful information.

3 months ago ·
My stupid face

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.

3 months 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

3 months ago ·

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

about 2 months 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.

about 2 months ago ·

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

about 1 month ago ·

Thank you for sharing the information very useful. It is very pleasant to read this article from your website.
obat kuat http://obatkuat.healthylifeindonesia.com/
obat kuat http://obatkuat.tasikstore.com/

about 1 month 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

about 1 month ago ·

Premature optimization!!!

about 1 month ago ·


5 days ago ·