Javascript Rest Parameter

Use-Cases of this Tutorial

  • You are looking to understand the Rest operator syntax used as function parameter.

Rest parameter syntax can be used in function declarations to compress passed arguments to an array. By using the Rest parameter syntax indefinite number of arguments can be passed to a function.

Using Rest Parameter in Functions

Rest parameter in a function declaration has ... (three dots) prefixed to it. This indicates that the parameter can be accessed as an array in the function. The number of elements in this array will be defined while calling the function.

We can understand the Rest syntax best with some examples.

  • Example #1

    // third parameter is basically a variable-length array
    function someFunc(a, b, ...c) {
    // prints 
    //	1
    //	2
    //	[3]
    someFunc(1, 2, 3);
    // prints
    //	1
    //	2
    //	[]
    someFunc(1, 2);
    // prints 
    //	1
    //	2
    //	[3, 4, 5]
    someFunc(1, 2, 3, 4, 5);

    As you can see the third parameter can be a variable length array. The first two parameters are passed as it is, and the rest of the user-given parameters are combined to an array.

  • Example #2 : We will define a function that can add any given numbers. The numbers to be added are passed as a Rest parameter — this helps us to calculate sum of any length of numbers.

    function calculateSum(...args) {
    	var total = 0;
    	args.forEach(function(x) {
    		total += x;
    // 1
    // 6
    calculateSum(1, 2, 3);

    The Rest parameter is an array, so you can use available array methods on it.

Rest Parameter Needs to be Passed as the Final Parameter

It is important to note that the Rest parameter always has to be last parameter in the function declaration.

Use-Cases of Rest Parameter

  • Many times we encounter situations where the number of parameters to be passed are not fixed. Rest parameter can be used in such cases.

  • Rest parameter can be helpful in code maintenance and future versions of an application. When an application is being upgraded to a new version, a common change occurs is that we may need to add extra parameters to a function. Considering such a scenario, we can implement Rest parameters from the first version itself so that in a future version the code changes may be minimal.
Javascript Spread Operator