With for..of introduced in ECMAScript 2015 (ES6), is there any reason to continue advocating use of the slightly older Array.prototype.forEach()
?
A lot
The most important difference is that you cannot break from a forEach
without throwing, which is using exceptions for flow control and therefore bad practice.
For an array loop that will always touch every element, for ... of
and forEach
are pretty equivalent. However, if you have a loop that is guaranteed to hit every element once, you can probably use map
or reduce
in place of any for-each construct and make things More Functional.
Your sum example is a great one for reduce
. forEach
is not the best choice, when you can just use:
let sum = values.reduce((sum, value) => sum + value, 0);
If you want to pick elements out of an array, you can typically use filter
. For flow control, every
and some
work, with inversion as necessary (as mentioned in the comments).
In general, forEach
can usually be replaced by a more descriptive and specialized array method, unless you specifically need to cause side effects. for...of
is very useful with iterable objects, but not always the best choice for arrays.