7

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

2
  • 2
    jsperf.com/for-vs-foreach/75 Commented Sep 12, 2013 at 20:33
  • 2
    forEach not supported by IE<9 Commented Sep 12, 2013 at 20:34

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

Beware of Array.prototype.forEach() if you're planning on using any polyfills/shims to provide prototype functionality to older browsers (I'm looking at you, InternetExplorer).

For example, the toString() method isn't available for arrays in older versions of IE. I have a polyfill that adds the toString() method to the Array.prototype in order for my application to work in older browsers. However, iterating with the .forEach() iterator also has access to (and will indeed iterate over) that method, in addition to iterating over the contents of your array.

In general though, for is much faster. If have JSON objects you'd like to loop through though, forEach is godsend.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.