To find the sum of an array of numbers with JavaScript, we call the reduce
method.
For instance we write
const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum);
to call reduce
with a function that returns the partialSum
plus the number a
in the array being looped through.
We set the initial value of partialSum
to 0 with the 2nd argument.
The sum is returned and it’s 6.