Sobes.tech
Junior

What is an arguments array in JavaScript?

sobes.tech AI

Answer from AI

arguments is a pseudo-array available inside the body of any regular function (but not arrow functions). It contains the values of arguments passed to that function when called.

Main characteristics:

  • Pseudo-array: Not a true array (Array). It has a length property and can be accessed by index (arguments[0], arguments[1]), but it lacks array methods (forEach, map, filter, etc.).
  • Indexed access: Elements are accessible by numeric indices starting from 0.
  • Dynamic: The contents of arguments correspond to the arguments actually passed during the call, regardless of the declared parameters of the function.
  • Deprecated: In modern JavaScript, using rest parameters (...) is the preferred way to handle an arbitrary number of arguments, as the rest operator returns a true array.

Example of usage:

function sumNumbers() {
  // Iterate over arguments using a loop
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

console.log(sumNumbers(1, 2, 3)); // Output: 6
console.log(sumNumbers(10, 20, 30, 40)); // Output: 100

Comparison with rest parameters:

function sumNumbersRest(...args) { // Using rest operator
  // args is a true array, so array methods can be used
  return args.reduce((total, num) => total + num, 0);
}

console.log(sumNumbersRest(1, 2, 3)); // Output: 6

Overall, arguments should be avoided in new code in favor of rest parameters for better readability and array method usage. However, knowledge of its existence is necessary as it can be encountered in legacy code.