Common Rest Parameter Patterns
You'll learn practical patterns where rest parameters shine: building variadic functions, creating wrapper functions, and implementing flexible array utilities.
Now that you understand rest parameters, let's explore the most common real-world patterns where they prove invaluable.
Variadic Functions
Functions that accept any number of arguments are called "variadic." Rest parameters make them elegant:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
Wrapper Functions
When you want to enhance or log another function without knowing its exact signature:
function loggedMax(...args) {
console.log('Finding max of:', args);
return Math.max(...args);
}
loggedMax(5, 12, 8, 3); // Logs array, returns 12
This pattern is perfect for middleware, logging, or adding behavior to existing functions.
Array Utilities
Building flexible array helpers that work with any number of inputs:
function createArray(...items) {
return [...items]; // Copy the items
}
function first(initial, ...rest) {
console.log('First:', initial);
console.log('Others:', rest);
}
first('a', 'b', 'c'); // First: a, Others: ['b', 'c']
Combining Named and Rest Parameters
The most powerful pattern: required arguments followed by flexible extras:
function formatMessage(template, ...values) {
return template + ' ' + values.join(', ');
}
formatMessage('Users:', 'Alice', 'Bob', 'Charlie');
// "Users: Alice, Bob, Charlie"
Key Takeaway: Rest parameters excel in three patterns: variadic functions (any number of similar arguments), wrappers (decorating existing functions), and array utilities (flexible collection operations). Always place rest parameters last and combine them with named parameters for clear, flexible APIs.