The rest parameter (…args) allows a function to accept an unlimited number of arguments as an array. The three dots (…) before the parameter name “collect” all remaining arguments into one array, which is convenient when you don’t know how many arguments will be passed.
// Function with rest parameter
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Usage
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
console.log(sum()); // 0The rest parameter is like a magical bag that can hold as many items as you want, and it will fit everything! The three dots (…) “collect” all arguments into one array, making it easy to work with them. 🎒
The rest parameter is a way to collect all function arguments into one array. It’s denoted by three dots (…) before the parameter name:
function showItems(...items) {
console.log('Items received:', items.length);
console.log('Items:', items);
}
showItems('apple', 'banana', 'orange');
// Items received: 3
// Items: ['apple', 'banana', 'orange']function greet(greeting, ...names) {
return greeting + ', ' + names.join(' and ');
}
console.log(greet('Hello', 'John', 'Peter', 'Mary'));
// 'Hello, John and Peter and Mary'function checkType(...args) {
console.log(Array.isArray(args)); // true
console.log(typeof args); // 'object'
console.log(args.length); // number of arguments
}
checkType(1, 2, 3); // true, 'object', 3// ✅ Correctly — rest parameter at the end
function correct(first, second, ...rest) {
// ...
}
// ❌ Error — rest parameter not at the end
// function wrong(...rest, last) {
// // SyntaxError!
// }// Mathematical operations
function multiply(...numbers) {
return numbers.reduce((result, num) => result * num, 1);
}
console.log(multiply(2, 3)); // 6
console.log(multiply(2, 3, 4)); // 24// Logging with variable number of arguments
function log(...messages) {
const timestamp = new Date().toLocaleTimeString();
console.log(`[${timestamp}]`, ...messages);
}
log('User', 'John', 'entered');
// '[10:30:15] User John entered'function oldWay() {
// arguments — not a real array
console.log(Array.isArray(arguments)); // false
// Need to convert: Array.from(arguments)
}
function newWay(...args) {
// args — real array
console.log(Array.isArray(args)); // true
args.map(item => console.log(item)); // Can use array methods
}// ❌ Error — rest not at the end
// function bad(param1, ...rest, param2) { }
// ✅ Correctly — rest at the end
function good(param1, param2, ...rest) { }The rest parameter is a convenient way to work with functions when you don’t know how many arguments will be passed to them. Modern and easy to use! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪