Use the Rest Operator with Function Parameters!

Tell us what’s happening:
Why can’t I use spread operator in const args ? “n” is also an array of arguments right?

Your code so far


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

Your browser information:

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

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

Well, args should be the function parameter . And you really don’t need const args = [...n]. You already have an array on which you can use reduce() on

You don’t need to declare another args array, just spread the function parameter “args” and then reduce your values in args to accumulate. In other words, delete const args = […n]; and replace your …n parameter with …args

1 Like

and what if i did the code this way:

const sum = (function() {
“use strict”;
return function sum(…s) {
return s.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3));

why not giving same result as i just replaced args with s ? ( im really new to coding :upside_down_face: )

the result is the same, and it works exactly the same, the tests ask specifically for the args parameter tho

1 Like

Perfect! thanks Prof.