Function Rest Parameter in JavaScript (ES6)
The rest parameter (...args
) is a new feature introduced in ES6 that allows a function to accept an indefinite number of arguments as an array. This is especially useful when you don’t know how many parameters will be passed to a function.
🔧 Syntax
function sum(a, b, ...args) {
// a and b are named parameters
// args is an array of remaining arguments
}
The rest parameter must always be the last in the function definition.
🧪 Example: Adding Multiple Numbers
function sum(...args) {
let total = 0;
for (let arg of args) {
total += arg;
}
return total;
}
let result1 = sum(6, 9, 34, 25, 29, 66, 77); // 246
let result2 = sum(6, 9); // 15
console.log(result1);
console.log(result2);
Explanation: All arguments passed to the sum()
function are collected in the args
array and then summed using a for...of
loop.
🚫 Incorrect Usage of Rest Parameters
The rest parameter must be the last in the parameter list. The following examples will throw syntax errors:
// ❌ Rest in the middle
function sum(a, ...rest, b) {
// SyntaxError
}
// ❌ Rest at the beginning
function sum(...rest, a, b) {
// SyntaxError
}
Correct Usage: The rest parameter should always appear at the end of the argument list.
📘 Real-World Use Case
Use rest parameters when writing utility functions where the number of inputs can vary:
function logMessages(...messages) {
messages.forEach(msg => console.log("Log:", msg));
}
logMessages("Server started", "User logged in", "Data loaded");
In this example, the function can handle logging any number of messages passed to it.
📘 Assignments: Practice Rest Parameters
- Create a function
multiplyAll(...nums)
that multiplies all the numbers passed to it. - Write a function
filterNumbers(...args)
that returns only the numbers greater than 10. - Try defining a function with rest parameters in the middle of the argument list. What error do you get?
- Write a function
logUserData(id, name, ...roles)
that logs user info and any number of assigned roles. - Compare rest parameter to spread operator in terms of direction: one collects, one expands.
📌 Summary
- Rest parameter
...args
collects all remaining arguments into an array. - Must be the last parameter in the function definition.
- Useful for functions with unknown or variable number of inputs.
- Improves code flexibility and reduces need for manual argument handling.