Signup/Sign In

JavaScript Rest Parameters

JavaScript Rest Parameters provides us with a way to declare a function which can take indefinite number of arguments, which are available as an array. In simple language, we can define JavaScript function with Rest Parameters which doesn't have a fixed number of parameters and can take any numbers of arguments when it is called.

For example, if I want to write a generic sum function, which can be used to add any number of values, which means it should work for sum(1, 2) function call, sum(1,2,3) function call, sum(1,2,3,4) function call etc.

JavaScript Rest Parameters Syntax

To use the Rest parameters syntax, we need to add ... as prefix to the name of the last parameter while defining the function.

function func_name(a, b, ...restArgs) {
    // statements
}

When we do so, all the additional arguments are provided to the function as an array, which can be then accessed inside the fuction defintion.

NOTE: Only the last parameter can be the Rest parameter.

Let's take a few examples and see the rest parameters in action.

JavaScript Rest Parameters Example:

In the first example, we will have a function which will take one simple parameter and one rest parameter. See the example below:

Try providing different values as argument when the test() function is called. Also, we can provide a single argument value or no argument value for rest parameter, in which case the array will have a single value of we will get an empty array inside the function.

Let's take another example, where we will have a function with only rest parameter.

function sortValues(...theArgs) {
    // using Array method on rest params
    let sortedArgs = theArgs.sort();
    return sortedArgs;
}

console.log(sortValues(11,2,5,13,1,9));


[1,2,5,9,11,13]

In the above example, we have a function which takes a single rest parameter. Also, as the rest parameter is nothing but an array, so all the Array methods can be used on it.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight