FAQ: Iterators - The .reduce() Method

Just to clarify, since accumulator and currentValue are placeholders in an anonymous function that’s being passed in as a callback function, I can just use any name arbitrarily correct?
Now as far as values go, I am assuming that they are being handled as positional arguments?
Their values are pre-defined according to their position in the function? First placeholder is the default position of the accumulator (which defaults to the first element in the array) and the second placeholder is the second element in the array?

Correct.

const sum = (a, b) => a + b;

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const arraySum = array.reduce(sum);

Also correct. The a above takes either the initial value (the value after the callback), when included, else the first element from the array. The b takes the next element, whether the second or the first.

Consider how this could be done manually.

1 a = initial_value
2 b = array.shift()
3 a += b

Loop through lines 2 and 3 until the array is exhausted. Return a.

1 Like