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 of code written in ES6 today contains code such as:
let sum = 0;
values.forEach((value) => {
sum += value;
});
In almost all of these situations, an equivalent for..of loop could be used instead:
let sum = 0;
for (let value of values) {
sum += value;
}
The more concise versions of the two formats:
values.forEach(value => sum += value);
for (let value of values) sum += value;
The for..of format works not only with Array
objects but other iterables as well and is more performant. Unlike Array.prototype.map()
there is also no return value to .forEach()
that would allow for further chaining.
It could conceivably be more readable and therefore useful at the end of a call chain (example below), or if each item should be applied to an unknown callback. Those edge cases aside, should it not be avoided?
['1', '2', 3].map(Number)
.forEach(value => sum += value)