JavaScript(JS) Rest Parameter
In JavaScript, the rest parameter is a feature that allows a function to accept an indefinite number of arguments as an array. It is denoted by three consecutive dots (...
) followed by a parameter name, which becomes an array containing all the additional arguments passed to the function.
Here's an example:
function sum(...numbers) { let total = 0; for (let number of numbers) { total += number; } return total; } console.log(sum(1, 2, 3)); // Output: 6 console.log(sum(4, 5, 6, 7, 8)); // Output: 30Source:www.theitroad.com
In the above example, the sum
function takes a rest parameter numbers
, which will contain an array of all the arguments passed to the function. The function then loops through this array to calculate the sum of all the numbers.
The rest parameter can also be used along with other parameters in a function, like this:
function multiply(multiplier, ...numbers) { return numbers.map(number => number * multiplier); } console.log(multiply(2, 1, 2, 3)); // Output: [2, 4, 6]
In this example, the multiply
function takes two parameters: multiplier
, which is the first argument passed to the function, and numbers
, which is the rest parameter that contains the remaining arguments as an array. The function then uses the map
method to return a new array containing the product of each number in the numbers
array and the multiplier
.