Why should forEach be preferred over regular iterators?

后端 未结 6 634
北荒
北荒 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条回答
  •  -上瘾入骨i
    2020-12-01 19:05

    The below is a list of advantages I see between the two.

    Advantages of "for of":

    1. In dev-tools, you can see the value of all variables in the function just by hovering. (with forEach, you need to change which stack-entry you're in to see variables not accessed within the loop function)
    2. Works on all iterables (not just arrays).
    3. You can use break or continue directly, instead of needing to use the some function and doing return true, which reduces readability. (can be emulated)
    4. You can use await within the loop, with the async/await context preserved. (can be emulated)
    5. Code within the loops can directly return out of the overall function. (can be emulated)

    Advantages of "forEach"

    1. It's a function call like map and filter, so it's easier to convert between the two.
    2. It doesn't need transpilation to be used in pre-es2015 contexts (just needs a simple polyfill). This also means you don't have to deal with odd "error catching" from the transpilation loop, which makes debugging in dev-tools harder.
    3. You can make a "custom forEach" method with added features. (here is a version that adds support for break, continue, return, and even async/await)
    4. It's a bit shorter. (for-of is 5 characters more if using const -- 3 if using let/var)

提交回复
热议问题