Use the Rest Operator with Function Parameters sos

Tell us what’s happening:
I got the code right but can someone explain why even though its taking two parameters and adding them when there is three still makes the code work.
Also what does the , 0 do in the code

Your code so far


const sum = (function() {
  "use strict";
  return function sum(...args) {
    return args.reduce((a, b) => a + b, 0);
  };
})();
console.log(sum(1, 2, 3)); // 6

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-the-rest-operator-with-function-parameters/

So there’s a few things going on here that seem to have you confused. And that’s not unusual, there’s a lot going on in this lesson.

First, the spread operator in the parameter turns any number of variables passed, into an array. By doing so, we can use array methods on them. There are a number of array methods we’ve learned at this point, things like .map and .filter, and .reduce is simply another array method.

If you haven’t yet, it might be a great idea to take a look at the docs on Array.reduce, either on MDN or on devdocs.io - it’s easy to get a little twisted when it comes to reduce.

So the signature for reduce is a little different. Where map and filter take a callback function, reduce takes two parameters: callback and initial_state. so that , 0 you’re asking about? that’s saying that, initially, our accumulator is zero.

Now, the callback being passed into reduce. It has been collapsed, a lot, but let’s expand it out and see if it makes a little more sense. I will change the variable names, but for the sake of reduce, when you see accumulator, think a from your function, and when you see member, think b.

return args.reduce(function(accumulator, member){
  return accumulator+member; // add the current value to our accumulator, each time through
}, 0 /* sets accumulator to zero on the first pass */)

I hate the collapsed form, using a and b and m for variable names. Saves keystrokes but LOUSY for self-documenting code. From the above, you can see more of what’s happening. Sane variable names.

That is, aside from variable names, exactly the same code as in your original, simply expanded out for readability. Either the fat-arrow function, or the traditional one, would work fine in this context.

Hope that helps!

1 Like

I was confused by this because the exercise regards to the rest operator and you’re mentioning the spread operator. I researched and found that the spread operator has more than one function, which explains a lot. Thanks for the explaining the reduce method

1 Like