In JavaScript, the rest parameter syntax allows you to represent an indefinite number of arguments as an array within a function parameter. It provides a convenient way to work with functions that can accept a variable number of arguments. The rest parameter is indicated by three dots (…) followed by a parameter name.
Syntax
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array:
function add(...elements){
let sum = 0;
for(let element of elements){
sum+= element;
}
return sum;
}
console.log(add(2,4,6)); //12
Get The Rest Elements in an Array
let snacks = ["meatpie", "sausage", "biscuit", "pizza"];
let drinks = ["coke", "malt", "sprite", "fanta"]
snacks.push(...drinks);
console.log(snacks);
De-structuring Assignment
Destructuring is the process of unpacking values from an array or properties from objects into distinct variables.
let a, b, rest;
[a, b] = [10, 20];
console.log(a); //10
console.log(b); //20
[a,b, ...rest] = [10,20,30,40,50];
console.log(rest) //Array[30,40,50]
Rest parameters are a powerful feature for writing flexible and readable functions in JavaScript.