JavaScript - MyArray.forEach nuances versus loop

I saw a lot of questions that suggest using:

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

instead:

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

for arrays due to inconsistent iteration ( see here ).




However, I cannot find anything like an object-oriented loop:

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

Which seems to me more intuitive.

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

  • Are there any differences between the loop standard (first example above) and the implementation of Array.prototype.forEach by modern browsers?
  • Is there a difference between modern browser implementations and the Mozilla implementation related to the above (with particular regard to IE8)?
  • Performance is not such a big problem, just consistency with which features are repeated.
+88
javascript iterator arrays for-loop internet-explorer-8
May 12 '14 at 16:19
source share
3 answers

The most significant difference between a for loop and a forEach method is that you can break out of the loop with the first. You can simulate continue by simply returning from the function passed to forEach , but there is no way to completely stop the loop.

In addition, these two effectively perform the same functions. Another minor difference is related to the scope of the index (and all contained variables) in the for loop due to the climb variable.

 // '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 much more expressive - it represents your intention to iterate through each element of the array and provides you with a link to the element, not just the index. In general, it mostly depends on personal taste, but if you can use forEach , I would recommend using it.




There are several significant differences between the two versions, especially regarding performance. In fact, a simple looping cycle works significantly better than the forEach method, as this jsperf test shows .

Regardless of whether you need such performance, you decide, and in most cases, I would prefer expressiveness over speed. This difference in speed is probably due to insignificant semantic differences between the main cycle and the method when working on sparse arrays, as indicated in this answer .

If you do not need forEach behavior and / or need to break out of the loop earlier, you can use Lo-Dash _.each as an alternative that will also work in a cross browser. If you use jQuery, it also provides a similar $.each , just notice the differences in the arguments passed to the callback function in each case.

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

+121
May 12 '14 at 16:40
source share

You can use your custom foreach function, which will work much better than Array.forEach.

You must add this once in your code. This will add a 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 Array.forEach

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

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

UPDATE: .forEach () performance has been improved in the new version of Chrome. However, the solution may provide additional performance in other browsers.

Jsperf

+12
Jan 4 '17 at 11:28
source share

Many developers (such as Kyle Simpson) suggest using .forEach to indicate that the array will have a side effect and .map for pure functions. For loops are suitable as a universal solution for a known number of loops or any other case that does not fit, since it is easier to communicate due to its wide support in most programming languages.

eg

 /* For Loop known number of iterations */ const numberOfSeasons = 4; for (let i = 0; i < numberOfSeasons; i++) { //Do Something } /* Pure transformation */ const arrayToBeUppercased = ['www', 'html', 'js', 'us']; const acronyms = arrayToBeUppercased.map((el) => el.toUpperCase)); /* Impure, side-effects with .forEach */ const acronymsHolder = []; ['www', 'html', 'js', 'us'].forEach((el) => acronymsHolder.push(el.toUpperCase())); 

From the point of view of the convention, this seems to be the best, but the community has not really settled on convention on a newer protocol for in iterating for in loops for in . Overall, I find it a good idea to follow the FP concepts that the JS community seems ready to accept.

+4
Sep 04 '16 at 1:24
source share



All Articles