Why should forEach be preferred over regular iterators?

后端 未结 6 641
北荒
北荒 2020-12-01 18:22

I was reading airbnb javascript guide. There is a particular statement, that says:

Don’t use iterators. Prefer JavaScript’s higher-order functions ins

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 19:18

    Majority of the time, the Airbnb styleguide tries to keep things consistent. This doesn't mean that there are never reasons to use a for loop or a for-in loop, like suppose you want to break out of the loop out early.

    The immutability comes into play when using a for loop to the change the value of something. Like reducing an array to an integer or mapping over elements to generate a new array. Using a built-in map, reduce, or filter, will not directly mutate the array's value directly so it's preferred. Using forEach over a for/for-in loop enforces the style consistency of using a higher order function over an iterator, so I believe that's why it's being recommended.

提交回复
热议问题