Yeah, reduce confuses a lot of people. It’s also really powerful once you get the hang of it.
reduce takes an array and “reduces” it to a single value.
Let me change the variable names and reformat a little:
args.reduce(
(acc, cur) => acc + cur, // callback function
0 // initial value
);
So, reduce starts with an initial value (0) and feeds each element of the array into the callback function. The callback function gets an “accumulator” and a “current element”. The cur is the current value of the array in this iteration. Whatever the callback returns becomes the new acc on the next iteration. At the end, the final value of the acc is returned from this method.
So, if our array is [12, 34, 56]
, then this what happens:
iteration 0:
acc passed to CB: 0 // the initial value
cur passed to CB: 12
returned by CB: 12 // 0 + 12
iteration 1:
acc passed to CB: 12 // returned from previous CB iteration
cur passed to CB: 34
returned by CB: 46 // 12 + 34
iteration 2:
acc passed to CB: 46 // returned from previous CB iteration
cur passed to CB: 56
returned by CB: 102 // 46 + 56
The final result is going to be 102 because this is the final value returned by the callback.
But see for yourself. Good developers like taking things apart and seeing how they work:
const result = [12, 34, 56].reduce(
(acc, cur, index) => {
console.log('\niteration', index)
console.log(' acc', acc)
console.log(' cur', cur)
const returnValue = acc + cur
console.log(' returning', returnValue)
return returnValue
}, 0);
console.log('\nresult:', result)
Mess around with that and see how it works.
Incidentally, this is a case where you can leave off the initial value. If you don’t pass an initial value, it will just use the first element and skip to passing the second element to the callback. Mess around with that and see how it works.