Rest Parameters in JavaScript
✨ What Are Rest Parameters?
Rest parameters allow a function to accept an indefinite number of arguments as an array. Introduced in ES6, they're declared using three dots ... followed by the parameter name.
Note
🔍 The rest parameter collects all remaining arguments into a single array!
🧪 Basic Syntax
Basic Usage of Rest Parameters
function logAll(...args) {
console.log(args);
}
logAll(1, 2, 3); // [1, 2, 3]🧠 Key Rules
- Rest parameter must be the last in the function’s parameter list.
- You can have only one rest parameter in a function.
- The collected arguments are stored in a real array (not array-like).
📌 Real-World Example: Adding Numbers
Summing All Arguments
function sum(...nums) {
return nums.reduce((total, num) => total + num, 0);
}
console.log(sum(10, 20, 30)); // 60🎯 Mixed Parameters + Rest
You can have regular named parameters before the rest parameter.
Fixed and Rest Parameters
function greet(greeting, ...names) {
return names.map(name => `${greeting}, ${name}!`);
}
console.log(greet("Hello", "Alice", "Bob"));
// ["Hello, Alice!", "Hello, Bob!"]🆚 Rest Parameters vs arguments Object
The old-school way to get all arguments was via the arguments object. But it's:
- Not a real array (no map, reduce, etc.)
- Not available in arrow functions
Note
✅ Use rest parameters instead of arguments for modern, clean code.
Comparing Rest and arguments
function oldWay() {
console.log(arguments); // array-like
}
function newWay(...args) {
console.log(args); // real array
}🧼 Use Cases
- Utility functions that operate on multiple inputs
- Flexible APIs with variable arguments
- Event handler wrappers and interceptors
🚫 Common Mistakes
❌ Wrong: Rest Parameter in the Middle
function badExample(...nums, extra) {
// SyntaxError!
}Note
❗ Always place rest parameters at the end of the parameter list.
🔗 Further Reading
>>“Use rest parameters to make your functions flexible and expressive—like open arms ready to embrace any number of inputs.”