Using the rest operator in function's parameter section

Using the rest operator in function's parameter section
0

#1

I’ve watched Beau’s videos and browsed MDN and w3 and I’m still not sure I understand the use of rest at least in the context of this particular lesson. Below is my attempt. What I think I have done is open the array of sum to args through modification of the function in return. I don’t think that I need to use it again further down, but I’m not really sure what to do and the little that I think I know about rest and spread assumes that I’m opening up the array up to a number of parameters through rest.

Help, por favor.


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

Problem Use the Rest Operator with Function Parameters
#2

Please do not ask a question about your own solution in another OP’s topic. I have moved your question to a new thread.

The …args creates an new array named which contains the function arguments as elements.

I have no idea why you wrote this line. You attempt to assign an new array to args which contains the values of 3 variables x, y, and z. However, you have no variables named x, y, and z so you will get a reference error. Plus, you can not declare args again, because it has already been declared in the parameter section.

Last, you through in …args for some reason here. Take that out, because the rest of the code on this line will sum the elements in args as long as you get rid of that const args = [x, y, z] I discussed before this part.


#3

I think you kind of have it but may be overthinking rest parameter. Rest parameter just packs up an undetermined number of parameters into an array that you can easily access in your function.


function myFunc(...args){
  console.log(args); // all param in array
}

myFunc(1,2,3);  
//[ 1, 2, 3 ]

myFunc("cow", "duck", "chicken", "pig");  
//[ 'cow', 'duck', 'chicken', 'pig' ]


////////////////////////
// and again with a named parameter
function myFunc2(first, ...theRest){
  console.log(first);
  console.log(theRest); // all but 1st param in array
}

myFunc2(1,2,3);
// 1
// [ 2, 3 ]

myFunc2("cow", "duck", "chicken", "pig"); 
// cow
// [ 'duck', 'chicken', 'pig' ]