Sub topic 9
The arguments Object and Why Arrows Lack It
This chapter assumes you know how to write function declarations, function expressions, and arrow functions. It also assumes you have seen how arrow functions take this from their surrounding scope, and that you know default and rest parameter syntax. Here we look at arguments, an older feature that sits next to those topics. It explains why rest parameters exist and why some legacy code fails when someone turns it into arrow functions.
What the arguments Object Is
Every regular function gets a local binding named arguments when it is called. A regular function here means a declaration, a function expression, or a method. arguments holds every value the caller passed, whether or not the function declared a parameter for it.
function showArgs() {
console.log(arguments.length); // 3
console.log(arguments[0]); // a
console.log(arguments[2]); // c
console.log(Array.isArray(arguments)); // false
console.log(typeof arguments.map); // undefined
}
showArgs('a', 'b', 'c');arguments is array-like. That means it has numeric indexes and a length property, but it is not an Array. It has none of the array methods such as map, filter, or reduce. It is iterable, though, so for...of and spread syntax work on it.
Converting arguments to a real array
Before rest parameters existed, code that wanted array methods had to copy arguments into an array first. You will still see all three of these patterns in older codebases:
function sumWithFrom() {
return Array.from(arguments).reduce((total, n) => total + n, 0);
}
function sumWithSpread() {
return [...arguments].reduce((total, n) => total + n, 0);
}
function sumWithSlice() {
return Array.prototype.slice.call(arguments).reduce((total, n) => total + n, 0);
}
console.log(sumWithFrom(1, 2, 3)); // 6
console.log(sumWithSpread(1, 2, 3)); // 6
console.log(sumWithSlice(1, 2, 3)); // 6The slice.call version is the oldest one. It borrows an array method and runs it with arguments as this. Array.from and spread replaced it.
arguments reports what was passed, not what was declared
arguments reflects the call site. Declared parameters and their defaults do not change it.
function withDefaults(a = 10, b = 20) {
return [arguments.length, a, b];
}
console.log(withDefaults()); // [ 0, 10, 20 ]
console.log(withDefaults(1)); // [ 1, 1, 20 ]
console.log(withDefaults(1, 2, 3)); // [ 3, 1, 2 ]The difference is sometimes useful. arguments.length tells you whether a caller passed undefined explicitly or passed nothing. A default parameter treats both cases the same way.
Why Arrow Functions Have No arguments
Arrow functions do not create their own arguments binding. They don't create their own this, super, or new.target either. Inside an arrow, arguments is an ordinary identifier, so JavaScript looks it up in the enclosing scopes like any other variable. If the arrow sits inside a regular function, it finds that function's arguments.
function outer() {
const inner = () => arguments[0];
return inner('ignored');
}
console.log(outer('from outer')); // from outerThe arrow was called with 'ignored', but it returns 'from outer'. The arrow's own argument is reachable only through a named or rest parameter.
The design follows from what arrows are for. An arrow is meant to be a lightweight callback that blends into its surrounding function. Taking this and arguments from that function means a callback inside a method can refer to the method's context without a const self = this or const args = arguments workaround.
The top-level gotcha
An arrow defined at the top level has no enclosing function. What happens next depends on where the code runs.
const countArgs = () => arguments.length;
try {
console.log(countArgs(1, 2, 3));
} catch (e) {
console.log(e instanceof ReferenceError);
}In a browser <script> or an ES module, this prints true, because there is no arguments to find. In a Node.js CommonJS file, it prints 5. Node wraps every CommonJS module in a function that receives exports, require, module, __filename, and __dirname, and the arrow picks up that wrapper's arguments. The CommonJS result is the more dangerous one. You get no error, just a plausible number that has nothing to do with your call.
Rest Parameters: The Replacement
A rest parameter (...args) does the main job of arguments and avoids its problems. It works the same way in arrows and regular functions.
const log = (level, ...messages) => `${level.toUpperCase()}: ${messages.join(' ')}`;
console.log(log('info', 'server', 'started')); // INFO: server started
console.log(log('warn')); // WARN:
function maxOf(...nums) {
return nums.length === 0 ? null : Math.max(...nums);
}
console.log(maxOf(3, 9, 4)); // 9
console.log(maxOf()); // null| Feature | `arguments` | Rest parameter `...args` |
|---|---|---|
| Type | Array-like object | Real `Array` |
| Array methods | No, must convert | Yes |
| Available in arrow functions | No (resolved lexically) | Yes |
| Contents | Every argument passed | Only arguments after the named ones |
| Clear from the signature | No, hidden | Yes, visible in the parameter list |
| Counted in `fn.length` | Not applicable | No, rest is excluded |
| Sloppy-mode aliasing with parameters | Possible | Never |
The "contents" row matters when you translate old code. arguments always includes the named parameters too. ...rest holds only what comes after them. A function that loops over arguments starting at index 1 becomes (first, ...rest) with a loop over rest starting at index 0.
Edge Cases in Legacy Code
Parameter aliasing in sloppy mode
In non-strict ("sloppy") code, a function with only simple parameters gets a mapped arguments object. Simple means no defaults, no rest, and no destructuring. In a mapped object, arguments[0] and the first parameter are two names for the same slot, so writing to one changes the other. Strict mode removes the mapping, and so does any non-simple parameter list.
Run this as a classic script, for example a .js file under Node's default CommonJS mode. ES modules and class bodies are always strict, and there the first line would print 1.
function sloppy(a) {
arguments[0] = 99;
return a;
}
function strict(a) {
'use strict';
arguments[0] = 99;
return a;
}
function nonSimple(a = 0) {
arguments[0] = 99;
return a;
}
console.log(sloppy(1)); // 99
console.log(strict(1)); // 1
console.log(nonSimple(1)); // 1Aliasing makes reassignment inside a function act at a distance, and it makes engines work harder. It is one reason modern code avoids arguments.
arguments.callee
Old recursive anonymous functions used arguments.callee to refer to themselves. In strict mode, reading arguments.callee throws a TypeError. A named function expression replaces it cleanly, as covered in the chapter on named function expressions.
'use strict';
const factorial = function () {
try {
return arguments.callee;
} catch (e) {
return e instanceof TypeError;
}
};
console.log(factorial()); // trueForwarding Arguments: The Common Refactor
arguments most often survives in wrappers that pass every argument through to another function. Here is the legacy version and its modern equivalent:
function legacyWrap(fn) {
return function () {
console.log('calling with', arguments.length, 'args');
return fn.apply(this, arguments);
};
}
function modernWrap(fn) {
return function (...args) {
console.log('calling with', args.length, 'args');
return fn.apply(this, args);
};
}
const calc = {
base: 10,
add(n) {
return this.base + n;
}
};
calc.legacyAdd = legacyWrap(calc.add);
calc.modernAdd = modernWrap(calc.add);
console.log(calc.legacyAdd(5)); // calling with 1 args, then 15
console.log(calc.modernAdd(5)); // calling with 1 args, then 15Look at what stayed the same: the returned wrapper is still a regular function. Turning it into (...args) => fn.apply(this, args) would fix the arguments problem, but this would then come from modernWrap's call, not from calc. The wrapper has to receive this dynamically, so it has to be a regular function. Rest parameters let you drop arguments without changing the function form. You can also write fn.call(this, ...args), which does the same thing.
Common Errors
- Converting a function that uses arguments into an arrow. The code then reads an outer function's arguments or throws. Add a rest parameter first.
- Calling array methods on arguments directly.
arguments.mapisundefined, so calling it throwsTypeError: arguments.map is not a function. Convert withArray.fromor switch to rest. - Assuming arguments.length counts declared parameters. It counts what the caller passed. Use
fn.lengthfor declared parameters, which excludes rest and anything from the first default onward. - Testing an arrow at the Node REPL or in a CommonJS file and seeing no error. The module wrapper's
argumentshides the bug. Code that worked there can throw in a browser or ES module.
Exercise
What does this code print when run as an ES module, and why? function outer() { const f = () => arguments.length; return f(1, 2, 3, 4); } console.log(outer('x'));
Show answer
It prints 1. The arrow f has no arguments binding of its own, so the identifier resolves to outer's arguments object, which holds the single value 'x'. The four values passed to f are not reachable inside it without a parameter.
Exercise
Rewrite this function using a rest parameter so it no longer uses arguments, keeping the same behavior: function tag(name) { const parts = []; for (let i = 1; i < arguments.length; i++) parts.push(arguments[i]); return name + ': ' + parts.join(','); }
Show answer
function tag(name, ...parts) { return name + ': ' + parts.join(','); } The rest parameter collects only the arguments after name, which matches the loop that started at index 1. Because nothing depends on this, it can also be written as const tag = (name, ...parts) => name + ': ' + parts.join(',');
Exercise
A teammate turns function () { return fn.apply(this, arguments); } inside a wrapper factory into (...args) => fn.apply(this, args). Arguments now forward correctly, but a method wrapped this way breaks. What went wrong, and what is the fix?
Show answer
The arrow takes this from the wrapper factory's scope, not from the object the wrapped method is called on, so fn runs with the wrong this. Keep a regular function and use only a rest parameter: function (...args) { return fn.apply(this, args); }.