Home » Tutorials » JavaScript » ES6 features: Rest Parameter

ES6 features: Rest Parameter

ES6 features: Rest Parameter

Rest Parameter is 1 of the core features of ES6. The Rest Parameter has a prefix of 3 dots (…) that allows you to represent an indefinite number of arguments as an array.

function rest(...args) {
    // ...

As you seen above, the 3 dots is Rest Parameter. All arguments that you pass to the function will map into an array.

rest('Peter', 'Jason', 'Donald', 'Joe');

The …args in the function rest stores the following values:

['Peter', 'Jason', 'Donald', 'Joe']


So , let’s say we have a calculation app that allows us to input as many value as we have, and sum up all the values:

function sum(...args) {
    let total = 0;
    for(const i of args){
        total += i;
    return total;
sum(1,2,3,4,5); // output 15

Assuming that, sometimes people might pass in different type of data into the sum() function, such as string, so in this case we need to filter out the data to number only.

function sum(...args) {
    return args.filter( (x) => typeof x === 'number')
               .reduce( (prev, current) => prev + current );
sum('He', 10, 10, '4D'); // output 20

In this example, we are using Array filter() function to filter the array args, and then we use reduce() function to reduces the array to sum up the value and output it as a single value.

You may also interested in: