HomeJAVASCRIPTWhat is the arguments object in JavaScript?

What is the arguments object in JavaScript?

In JavaScript, the arguments object is an array-like object that is automatically available inside every non-arrow function. It contains all the values (arguments) that were passed to the function when it was invoked, regardless of whether they were explicitly declared as parameters.

  • Every regular function (not arrow functions) automatically gets a local object called arguments.
  • It contains all arguments passed to the function, regardless of how many parameters the function actually defines.

Key Points about arguments:

  1. Array-like, not a real array
    • It has indexed elements (arguments[0], arguments[1], …) and a length property.
    • But it does not have array methods like .map(), .forEach(), etc. (unless converted to an array).
  2. Works only in regular functions
    • Arrow functions do not have their own arguments object. They inherit arguments from their nearest non-arrow function.
  3. Dynamic
    • It reflects the actual arguments passed at runtime, even if they don’t match the function’s declared parameters.

Example:

function demo(a, b) {
  console.log(arguments[0]); // first argument
  console.log(arguments[1]); // second argument
  console.log(arguments.length); // total arguments passed
  console.log(arguments); // full arguments object
}

demo(10, 20, 30);

Output:

10
20
3
[10, 20, 30]

Converting arguments to a real array:

function sumAll() {
  let args = Array.from(arguments); 
  return args.reduce((acc, val) => acc + val, 0);
}

console.log(sumAll(1, 2, 3, 4)); // 10

Modern Alternative → Rest Parameters (...args)

Since ES6, the recommended way is to use rest parameters instead of arguments:

function sumAll(...args) {
  return args.reduce((acc, val) => acc + val, 0);
}

console.log(sumAll(1, 2, 3, 4)); // 10

✅ Rest parameters give you a true array and work in both regular and arrow functions.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *