The most significant difference between a for loop and a forEach method is that you can break out of the loop with the first. You can simulate continue by simply returning from the function passed to forEach , but there is no way to completely stop the loop.
In addition, these two effectively perform the same functions. Another minor difference is related to the scope of the index (and all contained variables) in the for loop due to the climb variable.
// 'i' is scoped to the containing function for (var i = 0; i < arr.length; i++) { ... } // 'i' is scoped to the internal function arr.forEach(function (el, i) { ... });
However, I find that forEach much more expressive - it represents your intention to iterate through each element of the array and provides you with a link to the element, not just the index. In general, it mostly depends on personal taste, but if you can use forEach , I would recommend using it.
There are several significant differences between the two versions, especially regarding performance. In fact, a simple looping cycle works significantly better than the forEach method, as this jsperf test shows .
Regardless of whether you need such performance, you decide, and in most cases, I would prefer expressiveness over speed. This difference in speed is probably due to insignificant semantic differences between the main cycle and the method when working on sparse arrays, as indicated in this answer .
If you do not need forEach behavior and / or need to break out of the loop earlier, you can use Lo-Dash _.each as an alternative that will also work in a cross browser. If you use jQuery, it also provides a similar $.each , just notice the differences in the arguments passed to the callback function in each case.
(As for forEach polyfill, it should work in older browsers without problems if you decide to go this route.)
Alexis King May 12 '14 at 16:40 2014-05-12 16:40
source share