Rest ...Operator-DOnt get it

Tell us what’s happening:
I watched the video and not getting this rest operator, the example is very different from the setup code and yet using… on the const sum = […x,y,z]does not work.

Can someone please make this easier to understand?

Your code so far


const sum = (x, y, z) => {
const args = [x, y, z];
return args.reduce((a, b) => a + b, 0);
}

Your browser information:

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

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

Hello there.

Let us start with an impractical example:

// I want a function that can sum as many arguments as needed...
function summer(a, b, c=0, d=0, e=0, f=0, g=0, h=0) { //This could go on...
  return [a,b,c,d,e,f,g,h].reduce((a,b) => a + b, 0);
}
// Now, I can call like this (it requires a minimum of 2 arguments:
summer(1, 2, 3, 4) // Should return 10

NOTE: I had to assign default values to some of the parameters, to make them optional (will only work for addition/subtraction functions)

Or, we can use the rest operator:

function summer(...anyNumberOfArguments) {
  return [anyNumberOfArguments].reduce((a,b) => a+b, 0);
}
summer(1,2,3,4); // Should return 10

Hope this helps

1 Like

Hi,

Let say that you’re writing a function that is going to be called by someone else, and you have no idea what they are going to pass to your function, but whatever they pass, is important.

You know that x and y are mandatory values and they MUST be passed, otherwise the function won’t work.

function calculate(x, y, ...rest) {
   console.log(rest) // rest is an array
   return x * y + rest.length
}

calculate(2,4,7,2,3,4,5,6) // returns 14

Or you might want to write a function that takes any values passed to it and either displays them or sums them. Since the rest parameter is an array, you can use map() , filter() and reduce() on it. (You are not able to use those functions on any other type in Javascript) so as it was mentioned by Sky020, you do

function calculate(...args) {
   return args.reduce((a, b) => a+b)
}

calculate(2,5,6,7,8,5,7,8) // returns 48

Remember that it is called rest parameters but you don’t have to call it rest in your function parameters. It could be anything that you want it to be, as long as it’s the last parameter and has the ... before it.

1 Like