Your goal with the sum function you’re defining here is to sum all of the inputs. For example, if your inputs are 1, 2, and 3, their sum would be 1 + 2 + 3 = 6. When you sum, you are accumulating values.
Start with initial value = 1,
Add 2 and your accumulated value is 1 + 2 = 3.
Add 3 and your accumulated value is 3 + 3 = 6.
The reduce() method executes a reducer function that you provide. In this case, your reducer is (a, b) => a + b.
According to MDN Web Docs, the form of the reducer is: reducer = (accumulator, currentValue) => accumulator + currentValue;
In your case, a is accumulator, and b is currentValue.
The reduce method can take in a value set as the initial value. In the following case: array1.reduce(reducer, 5),
the initial value is 5.
In your case, the initial value is 0. When we start the accumulation (sum), we have: a = accumulator = 0. Our accumulator value starts as 0, but we need to add the currentValue, which at the start is 1. currentValue = b
So, a + b = 0 + 1 = 1.
In the next iteration, a is the accumulated value, which is 1, and the currentValue is 2. b = 2
So, a + b = 1 + 2 = 3
In the next iteration, a is the accumulated value, which is 3, and the currentValue is 3. b = 3
So, a + b = 3 + 3 = 6
As for passing in the arguments, according to MDN Web Docs:
" The rest parameter syntax allows us to represent an indefinite number of arguments as an array."
In sum(1, 2, 3), your arguments are 1, 2, and 3. The rest parameter syntax is used to represent the first and only parameter in your function definition of sum() Only the last parameter can be a rest parameter, but your only parameter is ...args, so it is taken as the last parameter. So, in your case, it takes all of your inputs (arguments) and puts them in an array: [1, 2, 3]
This allows us to apply the reduce() method, since it’s an array method.