Rest Operator with Function Parameters

Rest Operator with Function Parameters
0

#1

Have been working on the lesson with this ((SPOILER)ES6: Use the Rest Operator with Function Parameters) as a guide but I still don’t understand it. I don’t even see a rest operator in the instructions!


#2

The actual lesson is below. You linked to a forum post. Can you explain what part of the instructions are not clear to you?

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


#3

I’m the same, I don’t understand what I have to do here. I’ve tried using MSDN to understand rest and spread and also reduce since there haven’t been any lessons that I can recall up to this point that help me understand reduce before being asked to work with it.

Thanks in advance for your help! :slight_smile:


#4

I got the answer but I’m still not 100% sure how it works.

// original code to be changed
const sum = (function() {
  "use strict";
  return function sum(x, y, z) {
    const args = [ x, y, z ];
    return args.reduce((a, b) => a + b, 0);
  };
})();
console.log(sum(1, 2, 3)); // 6

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

So basically all I had to do was remove the args array and add …args into sum() ??
I’m glad I got the answer but I’m still clueless as to how I got it :sweat_smile:


#5

it’s so difficult for me to understand either…
especially don’t know why it need to return args.reduce ((a, b) => a + b, 0);
can someone please explain the second return, how is the function reduce? also how the function know variable (a,b) equal first 2 array and what is the 0 at the end?

i am beginner, very appreciate if anyone could help me this, thanks!


#6

Reduce takes a function and a initial value. So the function is like this:

function sum(a, b) {
  return a + b;
}

What reduce does is run that function for every value in the array, starting with that initial value (if you don’t give it a initial value, it uses the first value in the array). a is the accumulator, b is the current value in the array. Every time it runs, the result becomes the new value for a.

So say your array is [1,2,3,4] and your start value is 0.

sum(0, 1) is 1
1 is now the first value.
sum(1, 2) is 3
3 is now the first value.
sum(3, 3) is 6
6 is now the first value.
sum(6, 4) is 10
Now at the end of the array, final value is 10.


#7

Thanks you are awesome!
It is so clear and I totally understood now, cheers!