The rest operator

The rest operator
0

#1

Hi.

The rest operator, just like the map(), filter() and reduce() methods, isn’t well explained, which makes me wonder why.

I can’t understand how the rest operator works at all. I haven’t even a guess at how to attempt this exercise.


#2

Well, you should not depend on FreeCodeCamp only.
It’s also advised to Read, Search & Ask and you are doing a good job by asking the question.

The rest operator is easy to understand & it’s very useful when you do not know how many arguments are going to be received in a function call.

Let’s suppose you have a function called sum that returns the sum of two numbers only:

function sum (a,b) {
   return a + b;
}

To call it

sum(5,50);

Fine there’s no problem, you already know that it takes only two numbers a and b, but the problem is when you do not know how many numbers it’s going to receive; it could be 5, or 10 or 100 or only 2 (Variable)

The solution is to use the Rest Operator which takes: three points + the name of the operator like: ...args or ...theArg or anything you want.

The function with Rest Operator is going to be:

function sum(...arg) {
/* 
1) because ...arg is going to be an array, 
the best way to sum all the numbers in an array is? - Reduce!
2) The array can be accessed with the name given to 
the Rest Operator, in this case: arg 
*/

return arg.reduce(function(prev, curr) {
     return prev + curr;
})

}

sum(3,5,6,9,7,10,15,16);

It’s up to you, now, to convert the function given in the challenge into a function that accepts a variable number of parameters/arguments.


#3

clevious, thank you for your answer!
Thanking to your explanation I understood how the rest operator works.


#4

I agree up to the E6 Chapter FCC seemed pretty comprehensive then without warning jumps to this other level.

It is not immediately apparent that read and research will take place outside of FCC and forum. You think it is a warning not post stuff in the forum, without reading the forum.