Features of ES6 Part 4: Rest Parameters

Monday, August 18, 2014

A rest parameter allows a function to work with an unknown or variable number of arguments. A function’s rest parameter always appears at the end of the function’s argument list and uses a triple dot prefix (...), as shown below.

let doWork = function(name, ...numbers){
    let result = 0;
    
    numbers.forEach(function(n){
        result += n;
    });

    return result;
};

A caller invoking doWork can pass zero or more parameters at the rest parameter position. You can say the numbers argument will take “the rest” of the parameters a caller passes, and numbers will hold the parameter values in an array. In the following example, numbers will reference an array with the values 1, 2, 3.

let result = doWork("Scott", 1, 2, 3);
expect(result).toBe(6);

In the case where a caller passes no parameters in the rest parameter position, the rest parameter will be an empty array.

let doWork = function(...numbers){
    return numbers;
};

let result = doWork();
expect(result.length).toBe(0);

The Impact of Rest Parameters

Before ES6, we could allow callers to pass a variable number of arguments to a function by using the implicit arguments variable inside of the function. The arguments variable contains all the parameters to a function in an array-like object, but arguments is not an array, which creates confusion. It is also difficult to spot if a function is using arguments without reading through the code or documentation for the function.

ES6 rest parameters will avoid the confusion by always giving us a true array, and by using a dedicated syntax that makes rest parameters easy to spot when reading the function signature.

Want more? Watch JavaScript Fundamentals for ES6 on Pluralsight!


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!