Turning an Array into One Value
You have written loops that add up numbers: start a total at 0, then add each element to it. reduce does the same job as a method. It turns a whole array into one value:
const nums = [5, 3, 8];
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum);
Output:
16
reduce takes two arguments: a callback and a starting value (here 0). The callback gets the accumulator, which is the result so far, and the next element. It returns the new accumulator. reduce passes that value into the next call, and the accumulator after the last element is the answer.
Here is how [5, 3, 8] is added up, one call per row:
acc n acc + n
0 5 5
5 3 8
8 8 16
The starting value depends on the job. For a sum, start at 0. For a product, start at 1, because anything multiplied by 0 is 0:
console.log(nums.reduce((acc, n) => acc * n, 1));
console.log(nums.reduce((acc, n) => acc * n, 0));
Output:
120
0
The second line shows the mistake. With a starting value of 0, the product is always 0.
You can also leave out the starting value. Then reduce uses the first element as the starting accumulator and begins with the second element. This works well for finding the largest value:
console.log(nums.reduce((acc, n) => Math.max(acc, n)));
Output:
8
Should you use reduce or a loop? A short reduce, like a sum or a maximum, is easy to read. If the callback grows long, with several if statements inside, a for...of loop with a total variable is usually clearer. Both are good code.
In the exercise, use reduce to find the sum and the product of a line of numbers.