Rest Parameters

Rest parameters allow a function to accept an indefinite number of arguments as an array, providing flexibility when the exact number of inputs is unknown.

Illustration of rest_parameters
Illustration of rest_parameters

💡 What are Rest Parameters?

They collect all remaining function arguments into a single array, using the syntax ...variableName in the function definition.

Use rest parameters at the end of the parameter list to gather extra arguments:

📌 Deep Dive: Basic Syntax with Rest Parameters

JAVASCRIPT
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

sum(1, 2, 3, 4); // 10
sum(5, 10);      // 15
Output
10 and 15 respectively

Rest parameters differ from the arguments object:

Rest Parameters vs Arguments Object
Rest ParametersArguments Object
Array instance, supports array methodsArray-like but not an array (no array methods)
Only collects extra parameters as an arrayContains all arguments passed
Explicitly declared in function signatureImplicitly available inside functions
Works well with arrow functionsNot accessible in arrow functions

💡 Important Usage Tip

Rest parameter must be the last named parameter in the function signature. You can have zero or more named parameters before it.

Example combining named parameters and rest parameters:

📌 Deep Dive: Named + Rest Parameters

JAVASCRIPT
function showColors(firstColor, secondColor, ...otherColors) {
  console.log(firstColor);  // red
  console.log(secondColor); // blue
  console.log(otherColors); // ['green', 'yellow']
}

showColors('red', 'blue', 'green', 'yellow');
Output
red
blue
["green", "yellow"]

⚠️ Common Mistake

Placing rest parameters anywhere except the last position will cause a syntax error.

Rest parameters make functions more flexible, especially when dealing with variable amounts of input data.