Questions on "Use the Rest Operator with Function Parameters"

Questions on "Use the Rest Operator with Function Parameters"
0.0 0

#1

Tell us what’s happening:
I’m having some trouble here and wondering if someone can explain a few background questions?

In the example code, the function seems to work by 1) having “…args” as an argument and 2) referencing args inside the function. I thought that using “…” before “args” allows the input to be any length— can someone explain to me why the below code won’t work?

Your code so far


const sum = (function(...args) {
  "use strict";
   return function reducer = (accumulator, currentValue) => accumulator + currentValue;
  console.log(args.reduce(reducer));

}
console.log(sum(1, 2, 3)); // 6


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

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


#2

You have modified the original code in such a way that it now contains major syntax errors preventing the code from running at all.

The …args should be in the inner function returned.

The following line is attempting to mix traditional function declaration with arrow function syntax, but fails at both.

You can either define the inner anonymous function which gets returned using standard function declaration:

  return function(...args) {
     function reducer(accumulator, currentValue) {
       return accumulator + currentValue
     };
     return args.reduce(reducer);
   }

OR using ES6 arrrow function syntax:

   return (...args) => {
     const reducer = (accumulator, currentValue) => accumulator + currentValue;   
     return args.reduce(reducer);
   }