JavaScript Rest Parameters is a feature introduced in ES6 that allows us to pass an indefinite number of arguments to a function. This feature is used to pass an unlimited number of arguments to a function, and the rest parameter allows us to access the arguments as an array.
Rest parameters are a new feature introduced in ES6 that allows for a function to accept a variable number of arguments. They are indicated by three dots (...) followed by a parameter name. This parameter name can then be used to access all of the arguments passed to the function.
Rest parameters are especially useful when working with functions that can take an unknown number of arguments. Instead of having to iterate through all of the arguments and store them in an array, rest parameters allow you to easily access all of the arguments.
Let's look at an example. We have a function that takes two parameters, a name and an array of numbers. We want to be able to pass in an unknown number of numbers to the function. We can do this using rest parameters.
function printName(name, ...numbers) {
console.log(name);
console.log(numbers);
}
We can then call the function with any number of arguments.
printName('John', 1, 2, 3, 4);
We can also use the rest parameters to easily access all of the arguments passed to the function.
function printName(name, ...numbers) {
console.log(name);
console.log(numbers);
for (let num of numbers) {
console.log(num);
}
}
The rest parameters are stored in an array, so we can use the array methods to loop through and manipulate the data.
function printName(name, ...numbers) {
console.log(name);
console.log(numbers);
let sum = 0;
for (let num of numbers) {
sum += num;
}
console.log(sum);
}
As you can see, rest parameters are a great way to handle unknown numbers of arguments in a function. They make it easy to access and manipulate the data passed to the function.