for...of is more flexible. While forEach is a method on Array.prototype, for...of is a consistent syntax that can be used in more places.
For instance, iterables:
function *myIterable (v) {
while(--v) yield v
}
let launchCountdown = myIterable(60)
for (let i of launchCountdown)
console.log(`t minus ${i} seconds`)
So in effect arrays can be thought of as iterables in ES6. So IMHO it allows for more consistent behavior with the way iterators in other languages like Java and C++
Ah, I see, good point. And how would you handle cases (that I end up using quite often) such as :
arr.map(...).filter(...).forEach(...) which allows me to iterate over the filtered result? One would assign the result of filter to a variable and call for...of on that?
EDIT: Also, I never saw any mention of for...of working for object literals (à la `for (let [key, value] of obj`), I suppose that's out of scope, correct?
> arr.map(...).filter(...).forEach(...) which allows me to iterate over the filtered result?
Just like that. It would be pretty nice to have generic filter/map that can work on arbitrary iterables, but we don't have that right now. :(
> Also, I never saw any mention of for...of working for object literals (à la `for (let [key, value] of obj`)
for (let [key, value] of Object.entries(obj)) {
}
it's not in "ES6"/ES2015, but it's in ES2017 drafts and is implemented in Chrome and Firefox but so far not elsewhere. The need to do Object.entries instead of obj.entries() is annoying, but needed in case your literal has a property named "entries"... There's also Object.keys() and Object.values(), of course.
function* map(iterator, mapper) {
for (const elem of iterator) {
yield mapper(elem);
}
}
function* filter(iterator, filterer) {
for (const elem of iterator) {
if (filterer(elem)) {
yield elem;
}
}
}
function forEach(iterator, eacher) {
for (const elem of iterator) {
eacher(iterator);
}
}
function reduce(iterator, reducer, initial) {
let current = initial;
for (const elem of iterator) {
current = reducer(current, elem);
}
return current;
}