What is the arguments object, and what can you do with it?
The arguments object is a special object that you get inside every function that is not an arrow function. It holds the values that the caller passed in, in the order they were passed, and it also has a length property. It is not a real array, because it has no array methods such as map and filter.
function sum() {
console.log('how many arguments:', arguments.length);
console.log('type of the first one:', typeof arguments[0]);
console.log('is it a real array:', Array.isArray(arguments));
let total = 0;
for (const value of arguments) {
total += value;
}
return total;
}
console.log('result:', sum(1, 2, 3));
// Turn it into a real array when you need array behaviour.
function asArray() {
return Array.from(arguments);
}
console.log('as an array:', asArray('a', 'b'));
Because it behaves like an array, you can read it by index and you can walk through it with a loop. What you cannot do is call map or filter on it directly. The simple fix is to convert it first, either with Array.from(arguments) or with the spread operator [...arguments].
One of its quirks catches people out. In sloppy mode, the arguments object is linked to the parameter list, so changing a parameter also changes the matching entry in arguments, and the other way round as well. Strict mode removed that link, and because ES modules are always strict, the strict behaviour is the one you get in modern code.
Another quirk is the arrow function case. Arrow functions do not have an arguments object of their own. Inside an arrow function, the word arguments refers to the arguments object of the function that surrounds it, or it fails completely at the top level of a module where there is no surrounding function.
There is one more thing to know. The arguments object is not a replacement for a rest parameter when you only care about the first few arguments. The common pattern is to name the first parameter and then collect the rest, which gives you both, with a real array and no link between the parameters.