Let’s walk through it from the top.
First, we make a function, using ES6 syntax, called “sum”. It takes three arguments, x, y, and z, in parentheses. That’s the first line.
In the second line, we take those three arguments, and make an array out of them, and store them in the variable “args”.
In the next line, we use the “reduce” method on the “args” array by saying
args.reduce. The reduce method is going to take a function as an argument. Again, we’re using ES6 syntax. The function we’re using for reduce takes two arguments itself, “a” and “b”. THIS IS A TERRIBLE WAY TO NAME THESE ARGUMENTS, because “a” and “b” tells you nothing about what reduce does. “a” is the “accumulator”, or the total that gets incremented every time we process another piece of the array. “b” is the current value we’re on in the array. It might help to see it like this:
return args.reduce((accumulator, currentValue) => accumulator + currentValue, 0);}
The return value for the reduce function here is
a + b, so for every item in the array, we’re going to add that item to the accumulator. When we’re done, what we’re left with is a single value that gets returned. The 0 is the starting value for the accumulator.
In this case, we’re calling
sum(1, 2, 3). 1, 2, and 3 are the x, y, and z that get sent to the reduce function.
Step by step, here’s how it works.
The accumulator starts at zero. Our first value in the array is 1. So we add 1 and 0, for a total of 1.
Our accumulator is now 1, and we move to the next value in the array.
The next value is 2, so we add the accumulator, which is 1, and 2, to get 3.
Now our accumulator is 3.
Add accumulator and the next number in the array.
3 + 3 = 6
We’ve now gone through the whole array, so our final return value is 6.
Last of all, we print the value of sum(1, 2, 3) to the console so we can see the answer.