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 ?