Just ran into this myself and want to give this an answer with a more simple yet modern JavaScript example.
JavaScript's array reduce function iterates over an array (here list
) and reduces it to a new result (here sum
) by computing each item (here value
) in the array with the accumulator (here acc
):
const sum = list.reduce((acc, value) => acc + value);
Most reduce operations prefer to operate on an initial accumulator (second argument, also called initial value). In our example, it's indeed even mandatory, because otherwise the sum operation wouldn't work. We want to sum our values with an initial value of 0:
const sum = list.reduce((acc, value) => acc + value, 0);
The initial value for a reduce function is its second argument (here 0
). So if you come across the error:
TypeError: Reduce of empty array with no initial value
It just means that you have to provide an initial (empty) array for your reduce operation, because if you provide an empty array (here list
) to start with, it doesn't work and complains with this error. In order to fix it, provide an empty array as second argument:
const exponentials = list.reduce((acc, value) => {
acc = acc.concat(value * value);
return acc;
}, []);