Rest Parameters vs Array Parameters
You'll learn: When to gather arguments with rest parameters versus when to accept a single array explicitly.
The Choice Between Spreading and Packaging
At this point, you know how to use rest parameters (...args) to gather multiple arguments into an array. But sometimes you might wonder: should I use a rest parameter, or should I just ask the caller to pass an array directly?
The key difference is caller convenience versus internal clarity.
Rest parameters let callers pass arguments naturally:
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // Clean, natural call
Array parameters require the caller to construct the array explicitly:
function sumArray(numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
sumArray([1, 2, 3, 4]); // Caller builds the array
When to Use Each
Use rest parameters when:
- You want a clean, comma-separated call style
- Arguments are typically known at the call site
- You're building utility functions like
Math.max(...values)
Use array parameters when:
- The data already exists as an array
- You're processing collections from variables
- You want to emphasize that you're handling a collection, not individual items
Example distinction:
// Rest: clean for literal values
formatNames(...names: string[]): string
// Array: better when data is already grouped
processUserList(users: User[]): void
Key Takeaway: Rest parameters optimize for call-site convenience with individual values; array parameters are clearer when you're already working with collections. Choose based on how callers naturally have the data.