I am wondering: Is there any significant difference between forEach
and for
loop in JavaScript.
Consider this example:
var myArray = [1,2,3,4];
myArray.forEach(function(value) {
console.log(value);
});
for (var i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
Here is part of my research:
- Performance: According to JsPerf : forEach is little slower than for loop.
- Usability: There is no way we can break/return from the callback in case of forEach loop.
For example: You want to find out if a number is prime or not. I think using for loop is much more easier than using forEach loop to do this.
- Readability: Using for loop makes code more readable than having forEach in code.
- Browser compatibility: forEach is Not supported in IE < 9 So that introduces some shim in our code.
My questions are:
- What are the advantages of forEach over for loop ?
- In what scenarios, forEach is more preferable.
- Why did even it come into JavaScript ? Why was it needed at all ?
Best Answer
forEach
is a method on theArray
prototype. It iterates through each element of an array and passes it to a callback function.So basically,
forEach
is a shorthand method for the use-case "pass each element of anarray
to afunction
". Here is a common example where I thinkArray.forEach
is quite useful, compared to afor
loop:As you can see, the readability of the forEach statement is improved compared to a
for
loop.On the other hand, a
for
statement is more flexible: it does not necessarily involve an array. The performance of a normalfor
loop is slightly better, because there is no function call for each element involved. Despite of this, it is recommended to avoidfor
loops when it can be written as aforEach
statement.