For loop vs array.forEach in JavaScript
The for loop and forEach
The forEach and for loop can be used to accomplish effectively the same functionality for array. For example:
for (var i = 0; i < array.length; i++){ /* ... */ }
and
array.forEach(function(item, index){ /* ... */ });
Are there any difference between them?
The difference
The most substantive difference between the for loop and the forEach method are:
With for
- You may
breakout of the loop. - You may use the
continueto jump over iteration. - The performance is much faster than
forEach. - The scope of the index, for example i, is scoped to the containing function:
// 'i' is scoped to the containing function for (var i = 0; i < arr.length; i++) { ... }
With forEach
- You can simulate
continueby simply returning from the function passed toforEach. - However, there is no way to stop
forEachlooping altogether. - The performance is much slower than
for. - The scope of the index, for example i, is scoped to the internal function:
// 'i' is scoped to the internal function arr.forEach(function (el, i) { ... }); - However,
forEachis more expressive. It represents your intent to iterate through each element of an array, and it provides you with a reference to the element, not just the index.
Performance Test
The performance test is run across a jsperf.com test of a for loop vs foreach.
Here is the performance difference when running test in Chrome 47 on Mac OS X:
The scope of the index difference in details
Let’s say that I would like to do something asynchronous with the elements of an array.
// The array:
var elements = ["element1", "element2", "element3"];
This is how it is supposed to be implemented usingforEach:
elements.forEach(function(element) {
// The asynchronous action simulator
setTimeout(function() {
console.log(element);
}, 100);
});
Without knowing about forEach() I would start with a classic for(;;) loop:
for (var i = 0; i < elements.length; i++) {
setTimeout(function() {
console.log(elements[i]);
}, 100);
}
This doesn’t work as expected, because instead of element1, element2, and element3 on the console, I’m getting undefined three times. It seems that something is wrong with the i variable, because the function works fine with elements[0]. Actually, there is not nothing wrong with i. The thing is that its value is 3 when the console.log() is called and since elements[3] does not exist, it prints out undefined.
Reference & Resources
- http://zsoltfabok.com/blog/2012/08/javascript-foreach/
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync