Forwarding Arguments with Spread
You'll learn how to pass all arguments from one function to another using the spread operator, a key technique for building wrapper functions.
Sometimes you need to create a function that calls another function but adds some extra behavior—like logging, timing, or validation. The challenge is passing along all the arguments without knowing exactly what they'll be. This is where spreading arguments becomes essential.
The Core Idea
When you have an array (or rest parameter collection) and need to pass each element as a separate argument to a function, use the spread operator (...). This "unpacks" the array into individual arguments.
function add(a, b, c) {
return a + b + c;
}
function logAndAdd(...args) {
console.log('Arguments:', args);
return add(...args); // Forward all arguments
}
logAndAdd(2, 5, 8); // Logs: Arguments: [2, 5, 8]
// Returns: 15
Here, logAndAdd collects all arguments with rest parameters (...args), logs them, then spreads them into add().
Why It Matters
Without spread, you'd need to manually pass each argument or use .apply() (older technique). Spread makes wrapper functions clean and readable:
function timeFunction(fn, ...args) {
const start = Date.now();
const result = fn(...args);
console.log(`Took ${Date.now() - start}ms`);
return result;
}
timeFunction(add, 10, 20, 30); // Times the execution
This pattern works with any number of arguments—you're not hardcoding parameter counts.
Key Takeaway: Use spread (...args) to forward collected arguments to another function, enabling flexible wrapper functions that work regardless of how many arguments are passed.