Variadic Functions with Rest Parameters
You'll learn how to create functions that accept any number of arguments using rest parameters, making your function signatures incredibly flexible.
What Are Variadic Functions?
A variadic function is one that can accept a variable number of arguments—sometimes one, sometimes five, sometimes a hundred. In JavaScript, rest parameters (...args) make this pattern simple and readable.
Instead of forcing callers to pass exactly three arguments or requiring them to bundle values into an array, you use rest to collect however many they provide into a single array parameter.
Core Idea
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
sum(1, 2); // 3
sum(5, 10, 15); // 30
sum(1, 2, 3, 4, 5); // 15
The ...numbers syntax gathers all arguments into an array called numbers. Your function doesn't care how many you pass—it adapts automatically.
Why This Matters
Before rest parameters, you'd use the arguments object (which isn't a real array) or force callers to pass arrays explicitly:
// Old way:
myFunc([1, 2, 3]);
// Modern way with rest:
myFunc(1, 2, 3);
Rest parameters feel more natural and work seamlessly with array methods.
Combining Named and Rest
function greet(greeting, ...names) {
return `${greeting} ${names.join(', ')}!`;
}
greet('Hello', 'Alice', 'Bob', 'Charlie');
// "Hello Alice, Bob, Charlie!"
Here, greeting is fixed; the rest collects remaining arguments.
Key Takeaway:
Rest parameters (...args) let you build variadic functions that accept any number of arguments, automatically collecting them into an array for flexible, intuitive APIs.