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
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.
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.
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.
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.
They do two very different things:
for (var i=0; i<L.length; i++) { ... }
iterates over ALL indexes, including array elements that "are undefined".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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With