Use the Rest Operator with Function Parameters Bug?

Use the Rest Operator with Function Parameters Bug?
0.0 0

#1

Tell us what’s happening:

For all I know about this challenge, I’m doing this correctly. Just change the arguments of the sum function within the module to a spread operator and run the code. My code passes every test beyond ‘The sum function uses the … spread operator on the args parameter.’ Is there a bug with this challenge? It feels like it should be pretty straightforward. Is there a workaround? Should I just wait to finish this challenge until it’s fixed if it is indeed bugged? Or am I actually doing something wrong and don’t see it?

Your code so far


const sum = (function() {
  "use strict";
  return function sum(...num) {
    const args = [...num];
    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 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 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

After removing the comment, your code works. (I don’t know why)


#3

That’s weird, it’s good to know that I did the lesson correctly, but unfortunately it’s still not working on my end with or without comment. Even after clearing my cookies/cache and redoing it then. Thanks though!


#4

I’m on a phone and can’t check that this allows it to run and pass, but this line shouldn’t be there. Technically, everything should still work, but it kinda defeats the point of the rest arguments.

function sum (...num) {

num inside this function is represented as an array of the arguments passed into the function. You shouldn’t then make a copy of that array.

So inside your function, say you passed it 1, 2, 3 as args:

return function sum(...num) {
  // num is [1,2,3]
  const args = [...num];
  // args is a new [1,2,3]

args is pointless, there’s no reason for it to exist


#5

Oh, I didn’t know the spread operator as a function argument made an array like that, that’s very good to know!

Here’s my changed code, every test except for the last one still passes just as my other code did:

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

Thanks a bunch for the insight and correction on the spread operator!


#6

Ah, I think I can see why this is failing. Try using args as the name of the parameter, rather than num, so function sum(...args) { return args.reduce..... I think the tests should pass, that they are just being strict about the names you use


#7

Yep, that did it! Thanks again for your help.