Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rest and spread solution #67

Open
rickschmoo opened this issue Oct 29, 2015 · 1 comment
Open

Rest and spread solution #67

rickschmoo opened this issue Oct 29, 2015 · 1 comment

Comments

@rickschmoo
Copy link

Can someone comment on why ...args is necessary in the solution for ex 12 (rest and spread)? Why use that instead of a standard array?

i.e. the following two examples are equivalent. Why use one versus the other? Thanks!

...args version:

// write a function called `avg` here that calculates the average.
var avg = function(...args) {
  let thesum = args.reduce( (sum, n) => sum + n );
  return thesum / args.length;
}
console.log(avg(...args));

args version:

// write a function called `avg` here that calculates the average.
var avg = function(args) {
  let thesum = args.reduce( (sum, n) => sum + n );
  return thesum / args.length;
}
console.log(avg(args));
@ShadowManu
Copy link

Look that in each version you are using ...args (or args) in both the function definition and the function call. And that is basically the point: you can use either version depending on how you want the definition and separatedly the call to be.

They are indeed different, the exercise is call rest and spread because you are exercising on the Rest parameters and the Spread Operator.

The args version lets you use the same object (supposedly an array) when you call some function and treat it as that same object on the function definition. Nothing new, that's what we do in ES5.

The ..args versions is first destructuring the array on the function call (using the spread operator), and being recomposed in the function definition (using the rest parameters syntax).

So both versions basically do the same, and you could theorize the args one could be a little faster (no destructuring). But the main topic here is that you can use rest and spread when you got arguments and want parameters (or viceversa) and that could be changed either in call or definition, depending on the case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants