I have a question about the code below. I do not understand why an extra parameter is needed when adding sum + user.age. Is the zero the starting point for the accumulator? If so, shouldn’t it be possible to remove it and have reduce use the first age as the accumulator? Also, why is it there instead of passed as one of the arguments?
The accumulator is needed to keep track of the current sum value throughout iterations. And you’re correct, the 0 indicates that the initial value of sum should be 0, and if it’s omitted, the sum is initialised with the first value of the array. In this case, this would be an object with a name and age property, and the method would try to perform the addition Object + user.age, which is nonsensical. It can’t know that it should take the age property as initial value.
Its just how the reduce method is designed…reduce(callback {, optional initial value} ). It is passed as an argument to reduce, but not to the callback. Maybe the reason behind it, is the callback itself takes up to 4 parameters, adding the initial value as 5th would make combinations of the different parameters less comfortable.
As said. If you didn’t initialize the starting value to a number sum would initially be an object.
If you just add the age properties of the two objects together and return a number then on the next iteration the accumulator would be a number and would not have an age property (if I understand correctly what you are proposing).