Problem Statement
What are rest parameters? How do they differ from the arguments object?
Explanation
Rest parameters use three dots before the parameter name to collect all remaining arguments into a real array.
Unlike the arguments object which is array-like but not a real array, rest parameters are actual arrays with all array methods available.
Rest parameters must be the last parameter in the function signature.
They provide a cleaner way to handle variable number of arguments compared to the arguments object.
Arrow functions do not have arguments object, so rest parameters are the only way to access all arguments in arrow functions.
Rest parameters make code more readable and are preferred in modern JavaScript over the arguments object.
Code Solution
SolutionRead Only
// Rest parameters - real array
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Can use array methods
function getMax(...nums) {
return Math.max(...nums);
}
console.log(getMax(5, 2, 9, 1)); // 9
// Mixed parameters
function introduce(greeting, ...names) {
return greeting + ' ' + names.join(' and ');
}
console.log(introduce('Hello', 'John', 'Jane')); // 'Hello John and Jane'
// Arrow function with rest
const multiply = (...nums) => {
return nums.reduce((product, num) => product * num, 1);
};
console.log(multiply(2, 3, 4)); // 24
// Arguments object (old way)
function oldSum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
// arguments is array-like, not real array
// Does not work in arrow functions
// Rest vs arguments
function compare(...args) {
console.log(Array.isArray(args)); // true
console.log(args.map(x => x * 2)); // Works!
}