I can either do,
var arr = [];
arr.forEach(function(i) {
i;
});
for (var i = 0, length = arr.length; i < length; ++i) {
arr[i];
}
When should I use one over the other, is there performance differences?
I can either do,
var arr = [];
arr.forEach(function(i) {
i;
});
for (var i = 0, length = arr.length; i < length; ++i) {
arr[i];
}
When should I use one over the other, is there performance differences?
Share Improve this question asked Jun 4, 2013 at 18:02 user2251919user2251919 6752 gold badges11 silver badges23 bronze badges 6-
2
forEach
is slower, but it creates a scope for each iteration, which you manually have to do with a normalfor
(if you need one)...and also lets you set the value ofthis
in the callback (with its second parameter). It's also not supported in all browsers: kangax.github.io/es5-pat-table/#Array.prototype.forEach .forEach
also doesn't loop over empty items. Read more here: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… - it includes a polyfill for browsers that don't support it – Ian Commented Jun 4, 2013 at 18:05 - This partially answers your question: stackoverflow./questions/9329446/… – vasanth Commented Jun 4, 2013 at 18:05
- 1 To answer the performance question, create a performance test on jsperf. with 50,000 values in your array. Or executing 50,000 loops. – LarsH Commented Jun 4, 2013 at 18:05
-
forEach
is ECMAScript 5 -> patibility – Moritz Roessler Commented Jun 4, 2013 at 18:06 - 1 @Tim I see that one snippet has live output while the other has not - that might change the time required for the iteration. You know - they are lies, damn lies, and benchmarks. :) – Zsolt Szilagyi Commented Jun 4, 2013 at 18:22
1 Answer
Reset to default 10You use foreach whenever :
- your array is associtive or has gaps, i.e. you cannot reach every element by an incremented number (1,2,5, 'x', -7)
- you need to iterate in exactly the same order as they appear in the array. (e.g. 2,1,3)
- you want to be sure not the get into an endless loop
The last point is the main difference: foreach works on a copy, so even if you alter the elements, the array remains intact and can be iterated without defects.
That copy makes foreach somewhat slower than for, since it has to copy data. Keep in mind that some old or rare browsers don´t supports foreach, but they do support "for". Unless your array is really big (10.000 + items), ignore the speed difference. It´s in the milliseconds.
You use for whenever
- you want an easy way to aler the array you are moving on
- you want specific sequences, e.g. for ($i=100; $i < 1000; $i += 5) resulting in 100, 105, 110...