Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Nuances of myArray.forEach vs for loop

I've seen plenty of questions that suggest using:

for (var i = 0; i < myArray.length; i++){ /* ... */ } 

instead of:

for (var i in myArray){ /* ... */ } 

for arrays, due to inconsistent iteration (see here).


However, I can't seem to find anything that seems to prefer the object oriented loop:

myArray.forEach(function(item, index){ /* ... */ }); 

Which seems way more intuitive to me.

For my current project, IE8 compatibilty is important, and I'm considering using Mozilla's polyfill, however I'm not 100% sure how this will work.

  • Are there any differences between the standard for loop (the first example above) and the Array.prototype.forEach implementation by modern browsers?
  • Are there any difference between modern browser implementations and Mozilla's implementation linked to above (with special regard to IE8)?
  • Performance is not as much of an issue, just consistency with which properties are iterated over.
like image 888
Michael Lewis Avatar asked May 12 '14 16:05

Michael Lewis


People also ask

Is for loop faster than forEach JavaScript?

for...of loops are the fastest when it comes to small data sets, but they scale poorly for large data sets.

Which is better forEach or for loop?

This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

Is forEach slower than for loop JavaScript?

ForEach is 96% slower than for loop.


2 Answers

The most substantive difference between the for loop and the forEach method is that, with the former, you may break out of the loop. You can simulate continue by simply returning from the function passed to forEach, but there is no way to stop looping altogether.

Aside from that, the two accomplish effectively the same functionality. Another minor difference involves the scope of the index (and all containing variables) in the for loop, due to variable hoisting.

// 'i' is scoped to the containing function for (var i = 0; i < arr.length; i++) { ... }  // 'i' is scoped to the internal function arr.forEach(function (el, i) { ... }); 

However, I find that forEach is much more expressive—it represents your intent to iterate through each element of an array, and it provides you with a reference to the element, not just the index. Overall, it mostly comes down to personal taste, but if you can use forEach, I would recommend using it.


There are a few more substantial differences between the two versions, specifically regarding performance. In fact, the simple for loop performs considerably better than the forEach method, as demonstrated by this jsperf test.

Whether or not such performance is necessary for you is up to you to decide, and in most cases, I would favor expressiveness over speed. This speed difference is likely due to the minor semantic differences between the basic loop and the method when operating on sparse arrays, as noted in this answer.

If you don't need the behavior of forEach and/or you need to break out of the loop early, you can use Lo-Dash's _.each as an alternative, which will also work cross-browser. If you're using jQuery, it also provides a similar $.each, just note the differences in arguments passed to the callback function in each variation.

(As for the forEach polyfill, it should work in older browsers without problems, if you choose to go that route.)

like image 105
Alexis King Avatar answered Sep 22 '22 07:09

Alexis King


You can use your custom foreach function which will perform much better then Array.forEach

You should add this once to your code. This will add new function to the Array.

function foreach(fn) {     var arr = this;     var len = arr.length;     for(var i=0; i<len; ++i) {         fn(arr[i], i);     } }  Object.defineProperty(Array.prototype, 'customForEach', {     enumerable: false,     value: foreach }); 

Then you can use it anywhere like the Array.forEach

[1,2,3].customForEach(function(val, i){  }); 

The only difference it is 3 times faster. https://jsperf.com/native-arr-foreach-vs-custom-foreach

UPDATE: In new Chrome version the performance of .forEach() was improved. However, the solution can give the additional performance in other browsers.

JSPerf

like image 33
Seagull Avatar answered Sep 22 '22 07:09

Seagull