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.

💡 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
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
sum(1, 2, 3, 4); // 10
sum(5, 10); // 15
Rest parameters differ from the arguments object:
| Rest Parameters | Arguments Object |
|---|---|
| Array instance, supports array methods | Array-like but not an array (no array methods) |
| Only collects extra parameters as an array | Contains all arguments passed |
| Explicitly declared in function signature | Implicitly available inside functions |
| Works well with arrow functions | Not 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
function showColors(firstColor, secondColor, ...otherColors) {
console.log(firstColor); // red
console.log(secondColor); // blue
console.log(otherColors); // ['green', 'yellow']
}
showColors('red', 'blue', 'green', 'yellow');
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.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which syntax correctly defines a function using rest parameters?
Question 2 of 2
What type of object is created by rest parameters inside a function?
Loading results...