Rest parameter in ES6

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this ES6 example, we define function “adder” with a “rest parameter” called “numbers”.  Note the three dots before the parameter name in the function definition (instead of in the caller like the spread operator example).   This means that inside the function, we will have an array called “numbers” that contain all the values passed in from the caller.  The caller called “adder” with the parameters 4, 5, and 6.

rest parameters

The value 15 (the sum of 4, 5, and 6) is displayed in the browser because we iterate through each of the array values using the forEach method on arrays and accumulating it into a “sum” variable which we defined with the new ES6 keyword “let”.

You can have other parameters in the function beside the rest parameter.  The only condition is that the rest parameter must be last in the list of parameters.  Here, we have modified the function to have an additional name parameter…

more rest parameter

More ES6 features here.