Are there reasons to use array.forEach() over for…of, when both could be used, in ES6?

后端 未结 1 404
一整个雨季
一整个雨季 2020-12-11 09:06

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

相关标签:
1条回答
  • 2020-12-11 09:45

    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.

    0 讨论(0)
提交回复
热议问题