🟒 EasyFunctionsπŸ“– Theory Question

What are rest parameters and how do they differ from the arguments object?

πŸ’‘

Hint

Rest (...args) is a real Array; arguments is array-like, no arrow support, no Array methods

Full Answer

Rest parameters (...args) collect remaining function arguments into a real Array.

// Rest parameters β€” modern
function sum(first, ...rest) {
  console.log(first);   // 1
  console.log(rest);    // [2, 3, 4] β€” real Array!
  return rest.reduce((a, b) => a + b, first);
}
sum(1, 2, 3, 4); // 10
rest.map(x => x * 2); // βœ… has Array methods

// arguments β€” legacy
function old() {
  console.log(arguments);        // { 0:1, 1:2, ... } β€” array-LIKE
  console.log(arguments.map);    // undefined β€” NOT a real Array
  const arr = Array.from(arguments); // convert needed
}

// Arrow functions have NO arguments object
const arrow = () => {
  console.log(arguments); // ReferenceError!
  // Use rest: (...args) => { console.log(args) }
};

Key differences:

  • Rest is a real Array β†’ has all array methods
  • arguments is array-like β†’ no map/filter/etc
  • Arrow functions don't have arguments
  • Rest collects only the remaining args after named params
πŸ’‘ Always use rest parameters in modern code. arguments is legacy and has quirks that trip people up.

More Functions Questions

🟒 EasyWhat is the difference between call, apply, and bind?β†’πŸŸ’ EasyHow do arrow functions differ from regular functions?β†’πŸŸ’ EasyWhat is a pure function and why does it matter?β†’πŸŸ’ EasyWhat are Higher-Order Functions (HOF)?β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint