Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros/cons of iterating an array with Array.prototype.forEach() versus for() in Javascript

What are the pros/cons of iterating an array with Array.prototype.forEach() versus for() in Javascript?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

like image 326
Andrew Samuelsen Avatar asked Sep 12 '13 20:09

Andrew Samuelsen


People also ask

What is the difference between the array forEach () and array map () methods?

Differences between forEach() and map() methods:The forEach() method does not create a new array based on the given array. The map() method creates an entirely new array. The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.

Which is better forEach or for loop JavaScript?

forEach Loop It is faster in performance. It is slower than the traditional loop in performance. The break statement can be used to come out from the loop. The break statement cannot be used because of the callback function.

Which one is faster for or forEach or while?

while loops scale the best for large arrays. for...of loops are hands down the fastest when it comes to small data sets, but they scale poorly for large data sets. . forEach() and for...of were close enough that neither side should hang their hat on performance alone over the other.


2 Answers

forEach looks better sometimes and can avoid intermediate variables and closure problems.

for is faster, works on non-arrays, maintains this by default, and has always been part of JavaScript. You can also break out of it with break; — even nested.

In ES6, forEach’s this-maintaining and looks are improved by the introduction of =>; for’s verbosity and sometimes unintuitive scope is improved by let and for of loops.

As 6502 answered, they work differently on sparse arrays.
Do not use sparse arrays.

like image 183
Ry- Avatar answered Oct 14 '22 03:10

Ry-


They do two very different things:

  1. for (var i=0; i<L.length; i++) { ... } iterates over ALL indexes, including array elements that "are undefined".
  2. forEach iterates only on defined elements.

Note also that being "undefined" doesn't simply mean that the value of an element is undefined, but that the element as never been set and the two are very different things:

a = [];
a[3] = 9;
a.indexOf(undefined) // --> -1
a[1] = undefined;
a.indexOf(undefined) // --> 1

so you can have a defined element with value undefined...

a = [];
a[9] = 9;
a[3] = undefined;

a.forEach(function(){ console.log(arguments); });

will show two lines, one for element with index 9 and one for element with index 3

like image 22
6502 Avatar answered Oct 14 '22 02:10

6502