Explain Rest parameter in JavaScript.
Answer: In JavaScript, the Rest parameter allows you to represent an indefinite number of arguments as an array. It's useful when you want to handle a variable number of arguments in a function. Here’s how it works:
1. Syntax: The rest parameter is indicated by three dots ('...') followed by a parameter name, which gathers all the remaining arguments into an array.
function sum(...numbers) {
let total = 0;
for (let number of numbers) {
total += number;
}
return total;
}
2. Usage:
- You can use the rest parameter to collect all arguments after a certain point into an array.
- It must be the last parameter in the function parameter list because it collects all remaining arguments.
3. Example:
function multiply(multiplier, ...args) {
return args.map(x => multiplier * x);
}
console.log(multiply(2, 1, 2, 3)); // Output: [2, 4, 6]
In the example above:
- '...numbers' in the 'sum' function collects all arguments passed to 'sum' after the first one into an array named 'numbers'.
- '...args' in the 'multiply' function collects all arguments passed to 'multiply' after the first one into an array named 'args'.
This feature makes JavaScript functions more flexible and allows them to work with a varying number of arguments dynamically.
No comments:
Post a Comment