Rest parameter in Modern JavaScript ES6 Explained with Examples

The Rest parameter allows a function to accept an indefinite number of arguments as an array. With the help of a rest parameter, a function can be called with any number of arguments, no matter how it was defined. 

Syntax:

        
function function_name ( a, b, ...args) { 
     // Code 
}        
    

Without use of rest parameter

        
function addition(a, b){
         return a + b;
}

console.log(addition(1, 2));            // Output : 3
console.log(addition(1, 2, 3, 4, 5));   // Output : 3          
    

In the above code, no error will be thrown even when we are passing arguments more than the parameters, but only the first two arguments will be evaluated. It’s different in the case of the rest parameter. With the use of the rest parameter, we can gather any number of arguments into an array.

With use of rest parameter

 

        
function addition(...input){
    let sum = 0;
    for(let i of input){
        sum+=i;
    }
    return sum;
}

console.log(addition(1,2));          // Output : 3
console.log(addition(1,2,3));        // Output : 6
console.log(addition(1,2,3,4,5));    // Output : 15           
    

Argument Length - We can also check argument length using rest parameter.

        
function function1(...parameters) {
    console.log(parameters.length)
}

function1()              // Output : 0
function1(15)            // Output : 1
function1(25, 30, 7)     // Output : 3        
    

Sorting - we can also do sorting parameters with the use of rest parameters.

        
function sorting(...parameters) {
  let numbers = parameters.sort();
  return numbers;
}

console.log(sorting(5, 3, 7, 1))    // Output : Array [1, 3, 5, 7]        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top