Use the Rest Operator with Function Parameters-rest vs spread

Tell us what’s happening:
I get a test error saying I’m using the spread operator. Don’t understand–thought I was using the rest operator.

Your code so far


'use strict';
const sum = (...args) => 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/70.0.3538.110 Safari/537.36.

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

I’m not sure why this code is so complicated, but as you’ve tried to simplify it, you broke the test. Don’t do more than the test requires. It wants you to change the existing code to use a spread operator - nothing more, nothing less.

So, reset the code and make the simple change. Make a change on line 3 and remove or comment out line 4. That’s all you need to do.

1 Like

Thanks. That worked. On to more challenges!

I am having the same issue when running the test. The console displays “The sum function uses the … spread operator on the args parameter.”

I used the advice provided above by changing line 3, commenting out line 4, but you still need to update line 5. I still receive the same error.

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

I decided to change from using “x” to “args” and it worked. Seems to me that it should allow any name to produce the correct result.

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

I agree that x should work in JavaScript. But I disagree that it would pass the test. While the instructions are a little vague:

Modify the function sum so that it uses the rest operator and it works in the same way with any number of parameters.

The test that you are failing is not:

The sum function uses the ... spread operator on the args parameter.

Part of being a dev is paying very close attention to every small detail.

Should it be required to be called args? That is debatable, but I think it is a better name than x. Variable naming is an important thing. I should be able to look at a variable name and know what the variable is. With the exception of iterations variables like i, j, and k and parameters for very short anonymous callback functions, you shouldn’t use one letter variable names.

2 Likes