As far as performance goes, the for loop is the fastest option. If you want readability this reduce example is pretty sweet, I'd use it. I believe for...of loops are somewhere in between regarding performance but I tend to avoid them.
Now, I believe reduce makes code hard to grasp most of the time, as 90% of its uses could be replaced by a different method. Since I stopped using Ruby my reduce usage has dropped considerably. Great for getting the sum of an array - probably bad for most other things.
Observation:
I was seeing the pattern of iterables and iterators. In C# the iterators would have just one name, with multiple overrides. This is why I asked about the distinction.
In JavaScript the forEach function would be the most fundamental built-in function to the array, with 'map' and 'reduce' and 'filter' giving (decorated) patterns of a fundamental iterator. All could be considered 'iterators'
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Both of these are incorrect anyway.
The reduce example should be written like this:
Or slightly more readable:
And hell you could skip the second parameter (0) in this case as it would work regardless.
So the complete example would be:
As far as performance goes, the for loop is the fastest option. If you want readability this reduce example is pretty sweet, I'd use it. I believe for...of loops are somewhere in between regarding performance but I tend to avoid them.
Now, I believe reduce makes code hard to grasp most of the time, as 90% of its uses could be replaced by a different method. Since I stopped using Ruby my reduce usage has dropped considerably. Great for getting the sum of an array - probably bad for most other things.
Case in point, the example in the OP says:
But you could simply do this:
I know it's simply to illustrate its usages but my point is it's harder to understand.
Neat
Observation:
I was seeing the pattern of iterables and iterators. In C# the iterators would have just one name, with multiple overrides. This is why I asked about the distinction.
In JavaScript the forEach function would be the most fundamental built-in function to the array, with 'map' and 'reduce' and 'filter' giving (decorated) patterns of a fundamental iterator. All could be considered 'iterators'