/    /  Javascript-Rest parameters

Javascript-Rest parameters

 

The Rest parameter is an improved way to handle function parameter and allowing us to easier to handle different input as parameters in a function. The rest parameter syntax allows us to provide an indefinite number of arguments as an array. With the help of a rest parameter, a function can be return with any number of arguments and no matter how it was defined. Rest parameter is added in ES2015 (ES6) which improved the ability to handle parameter.

 

Syntax:

 

function functionname[...parameters]//... is the rest parameter
{
statement;
}

 

how the rest parameter works:

 

// Without rest parameter
function fun(a, b){
       return a + b;
}
console.log(fun(1, 2)); // 3
console.log(fun(1, 2, 3, 4, 5)); // 3  

Javascript-Rest parameters

 

no error will be thrown even when you are passing arguments more than the rest parameters. Only the first two arguments will be evaluated.

 

// es6 rest parameter
function fun(...input){
       let sum = 0;
       for(let i of input){
                sum+=i;
       }
       return sum;
}
console.log(fun(1,2)); //3
console.log(fun(1,2,3)); //6
console.log(fun(1,2,3,4,5)); //15  

Javascript-Rest parameters

 

get the sum of all the elements that we enter in the argument when we call the fun() function.

 

we have use of the rest parameter with some other arguments inside a function.

 

// rest with function and other arguments
function fun(a,b,...c){
       console.log(`${a} ${b}`); //Mukul Latiyan
       console.log(c); //[ 'Lionel', 'Messi', 'Barcelona' ]
       console.log(c[0]); //Lionel
       console.log(c.length); //3
       console.log(c.indexOf('Lionel')); //0
}
fun('Mukul','Latiyan','Lionel','Messi','Barcelona');

Javascript-Rest parameters