JavaScript […Rest] Parameters
MDN documentation definition: “The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.”
To define a rest parameter in a function, we use the spread operator (...) followed by a parameter name, which will capture all remaining arguments passed to the function as an array. Here's an example:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
console.log(sum(5, 10)); // Output: 15In the above example, the sum function takes any number of arguments and returns their sum. The rest parameter numbers captures all arguments passed to the function as an array, which we can then use with the reduce method to compute the sum.
Get Verakulemina’s stories in your inbox
Join Medium for free to get updates from this writer.
Rest parameters can also be used in object and array destructuring. Let’s take a look at some examples.
Using Rest Parameters in Object Destructuring
const person = {
name: "John",
age: 30,
gender: "male",
country: "USA",
};
const { name, age, ...info } = person;
console.log(name); // Output: "John"
console.log(age); // Output: 30
console.log(info); // Output: { gender: "male", country: "USA" }In the above example, we use object destructuring to extract the name and age properties from the person object, and capture the remaining properties (gender and country) in the info object using the rest parameter syntax.
Using Rest Parameters in Array Destructuring
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]In this example, we use array destructuring to extract the first two elements of the numbers array, and capture the remaining elements in the rest array using the rest parameter syntax.
In conclusion, rest parameters in JavaScript are a powerful and flexible feature that can help us write more expressive and concise code. By using the spread operator with a parameter name, we can capture any number of arguments passed to a function as an array, or extract and capture properties from objects and arrays in a more convenient way.










