javascript - Are there reasons to use array.forEach() over for...of, when both could be used, in ES6? -
with for..of introduced in ecmascript 2015 (es6), there reason continue advocating use of 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 of these situations, equivalent for..of loop used instead:
let sum = 0; (let value of values) { sum += value; } the more concise versions of 2 formats:
values.foreach(value => sum += value); (let value of values) sum += value; the for..of format works not array objects other iterables , more performant. unlike array.prototype.map() there no return value .foreach() allow further chaining.
it conceivably more readable , therefore useful @ end of call chain (example below), or if each item should applied unknown callback. edge cases aside, should not avoided?
['1', '2', 3].map(number) .foreach(value => sum += value)
the important difference cannot break foreach without throwing, using exceptions flow control , therefore bad practice.
for array loop touch every element, for ... of , foreach pretty equivalent. however, if have loop guaranteed hit every element once, can use map or reduce in place of for-each construct , make things more functional.
your sum example great 1 reduce. foreach not best choice, when can use:
let sum = values.reduce((sum, value) => sum + value, 0); if want pick elements out of array, can typically use filter. flow control, every , some work, inversion necessary (as mentioned in comments).
in general, foreach can replaced more descriptive , specialized array method, unless need cause side effects. for...of useful iterable objects, not best choice arrays.
Comments
Post a Comment