Problem Statement
What is the difference between rest parameters and the arguments object?
Explanation
Rest parameters collect all remaining arguments into a real array with all array methods available.
The arguments object is array-like but not a real array. It does not have array methods like map or filter.
Rest parameters must be the last parameter. Arguments object includes all parameters.
Arrow functions do not have arguments object, so rest parameters are the only way.
Rest parameters provide cleaner, more modern syntax than arguments.
Always prefer rest parameters in modern JavaScript code.
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
console.log(sum(5, 10)); // 15
// numbers is a real array
function demo(...args) {
console.log(Array.isArray(args)); // true
console.log(args.map(x => x * 2)); // Works!
}
// Mixed parameters with rest
function greet(greeting, ...names) {
return `${greeting} ${names.join(' and ')}`;
}
console.log(greet('Hello', 'John', 'Jane', 'Bob'));
// 'Hello John and Jane and Bob'
// ARGUMENTS OBJECT - array-like
function oldWay() {
console.log(Array.isArray(arguments)); // false
// arguments.map(); // Error! No map method
// Convert to array
const arr = Array.from(arguments);
// or
const arr2 = [...arguments];
// or
const arr3 = Array.prototype.slice.call(arguments);
}
// Arrow functions have NO arguments object
const arrowFunc = () => {
// console.log(arguments); // ReferenceError!
};
// Must use rest parameters in arrow functions
const arrowSum = (...nums) => {
return nums.reduce((a, b) => a + b, 0);
};
// PRACTICAL EXAMPLES
// Logger with variable arguments
function log(level, ...messages) {
const timestamp = new Date().toISOString();
console.log(`[${level}] ${timestamp}:`, ...messages);
}
log('ERROR', 'Database error', 'Connection failed');
// Flexible calculator
function calculate(operation, ...nums) {
switch(operation) {
case 'add':
return nums.reduce((a, b) => a + b, 0);
case 'multiply':
return nums.reduce((a, b) => a * b, 1);
default:
return 0;
}
}
console.log(calculate('add', 1, 2, 3, 4)); // 10
console.log(calculate('multiply', 2, 3, 4)); // 24
// Destructuring with rest
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
const {a, b, ...others} = {a: 1, b: 2, c: 3, d: 4};
console.log(others); // {c: 3, d: 4}
// Function accepting unlimited callbacks
function executeAll(...callbacks) {
callbacks.forEach(cb => cb());
}
executeAll(
() => console.log('First'),
() => console.log('Second'),
() => console.log('Third')
);