**Rest parameters** collect all remaining arguments into a real Array. They must be the **last parameter** in the function signature. Unlike the old `arguments` object, rest parameters are a true Array with all array methods, and they work in arrow functions.
1Understanding Rest Parameters (...)
Rest parameters collect all remaining arguments into a real Array. They must be the last parameter in the function signature. Unlike the old arguments object, rest parameters are a true Array with all array methods, and they work in arrow functions.
Rest parameters replace the 'arguments' object. Use rest parameters in all new code.
// Rest collects remaining arguments
function logMessages(level, ...messages) {
messages.forEach(msg => {
console.log(`[${level}] ${msg}`);
});
}
logMessages('INFO', 'Server started', 'Listening on port 3000');2Practical Example
Here is a real-world application of Rest Parameters (...) showing how it is used in production JavaScript code.
// Rest in arrow functions (unlike arguments!)
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3, 4, 5)); // 15
// Destructuring with rest
const [first, second, ...remaining] = [1, 2, 3, 4, 5];
console.log(first, second, remaining); // 1 2 [3,4,5]3Best Practices
Follow these guidelines when working with Rest Parameters (...):
1. Rest must be the last parameter
2. Use rest instead of arguments for better clarity and arrow function support
3. Combine with regular params for the first few fixed arguments
Tip: Rest parameters replace the 'arguments' object. Use rest parameters in all new code.
// Rest collects remaining arguments
function logMessages(level, ...messages) {
messages.forEach(msg => {
console.log(`[${level}] ${msg}`);
});
}
logMessages('INFO', 'Server started', 'Listening on port 3000');