The rest parameter is introduced in ECMAScript 2015 or ES6, which improves the ability to handle parameters. The rest parameter allows us to represent an indefinite number of arguments as an array. By using the rest parameter, a function can be called with any number of arguments.
Before ES6, the arguments object of the function was used. The arguments object is not an instance of the Array type. Therefore, we can't use the filter() method directly.
The rest parameter is prefixed with three dots (...). Although the syntax of the rest parameter is similar to the spread operator, it is entirely opposite from the spread operator. The rest parameter has to be the last argument because it is used to collect all of the remaining elements into an array.
function fun(a, b, ...theArgs) { // statements }
function show(...args) { let sum = 0; for (let i of args) { sum += i; } console.log("Sum = "+sum); } show(10, 20, 30);
All the arguments that we have passed in the function will map to the parameter list. As stated above, the rest parameter (...) should always be at last in the list of arguments. If we place it anywhere else, it will cause an error.
The rest parameter with the following syntax will cause an error.
function show(a,...rest, b) { // error };
The rest parameter and arguments object are different from each other. Let's see the difference between the rest parameter and the arguments object:
Destructuring means to break down a complex structure into simpler parts. We can define an array as the rest parameter. The passed-in arguments will be broken down into the array. Rest parameter supports array destructuring only.
By using the rest parameter, we can put all the remaining elements of an array in a new array.
Let's see an illustration of the same.
var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"]; // destructuring assignment var [a,b,...args] = colors; console.log(a); console.log(b); console.log(args);
JavaScript allows us to create dynamic functions by using the function constructor. We can use the rest parameter within a dynamic function.
let num = new Function('...args','return args'); console.log(num(10, 20, 30));