An Introduction to the Javascript Rest Parameter Syntax

javascript
Published on July 16, 2019

Use-Cases of this Tutorial

  • Understand the Rest operator syntax used while passing function parameters.
  • Know how to pass any number of parameters while calling a function.

Javascript 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 : In the below code the third parameter for the function 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.

    // third parameter is basically a variable-length array
    function someFunc(a, b, ...c) {
    	console.log(a);
    	console.log(b);
    	console.log(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);
    
  • 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;
    	});
    
    	console.log(total);
    }
    
    // 1
    calculateSum(1);
    
    // 6
    calculateSum(1, 2, 3);
    

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

Note : 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.
In this Tutorial