Javascript - .reduce()
Code Life
By Pierre Marsaa
Boiling a List Down to One Value
Imagine you want to calculate the total HP of your entire Codémon team. Instead of getting back another array, you want to combine all the items in the list into a single value (like a sum or a total score).
With .forEach(), you would create a variable outside the loop and add to it at each step:
↗️
Loading editor...
↶
↷
The .reduce() method does this exact job directly, without needing an external let variable. It carries a running result from one element to the next and returns the final value at the end:
↗️
Loading editor...
↶
↷
Verify