Can't understand what is accumulator in .reduce() method

Hi! I just don’t get what is an accumulator and how do I get it. For example, here is a screenshot from exercise:

Can someone explain me a bit more, what exactly is accumulator? I think it’s just language barrier messing up here with me so I don’t get it right away.

After looking a bit more in a example I see, that, if we sum first iteration’s accumulator + currentValue we get second iteration’s accumulator. The same with next iteration’s accumulator. But it still doesn’t make any sense for me. Why value 3 wasn’t used in example as value of currentValue? And why it didn’t start from the currentValue 1?

The .reduce method is an array iterator that reduces our array down to a single value. When it does this, it either needs an initial value, or takes the very first element of the array as the initial value. So in this case, an initial value has not been defined therefore it takes the first element 1 as the initial value.

The accumulator is essentially the place where the continuously reduce array value is stored. So in this example, your initial value is the 1, so accumulator starts with the value of 1. Then the iterator carries out the first operation, summing this accumulator value of 1 with the currentValue, which in this case starts at the second element of the array 2. Thus after 1 iteration, 3 is returned. the next iteration then takes the value of accumulator = 3, and repeats i.e. 3 + 4 which is 7. Then for our final element it does the same again, so 7 + 10 = 17, hence the output returns 17.

Hope that makes sense!

1 Like

Yes, it did help a lot. Now I can kinda see the idea and how it works. I’ll reread what you’ve replied couple of times and I will definitely start understanding this method normally! Thanks