Rest Parameter With Parameters

Tell us what’s happening:
Can someone walk me through what’s actually happening here the value entered as parameters in the piece of code : arg.reduce((a, b) => a +b));

What does reduce mean and how does any value I add go through this function to result in addition?

Your code so far

const sum = (...args) => 

args.reduce((a, b) => a + b, );

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.68.

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

Of all the prototype methods, reduce confuses people the most. But is also very powerful. It is for when you want to take an array and reduce it dow to a single value.

As to the parameters, the first one is often called the “accumulator”. As you go through the array, it will keep a running total (in this case). The second parameter is often called the “current” - it is the current value of that array element as you iterate through. In this case, with each iteration, it adds the running total to the current element (a + b).

There are a few other little things, but those are simple once you understand the above.

Here’s an illustration:

A function you pass to the reduce function requires two parameters. In the illustration, I name them acc (for accumulator) and item. Reduce will apply the passed function for every element in the array. The value of the acc is passed on to the next iteration. This is how the answer is built. The result of the reduce function is the value of acc at the end.

You can pass the initial value of acc as the second argument to reduce. If the initial value is not specified, as in this case, the first element in the array is assigned to acc (10 in this example).

The reduce function is really neat. Suppose I want to find a max of an array elements, all I have to do is change the expression acc + item to Math.max(acc, item). If I want to return a reverse of a given list, then simply write


and pass an empty list as the initial value.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.