The arguments keyword
What arguments is
argumentsis a built-in object available inside any regular function (but not an arrow function). It contains all the arguments passed to that function on call.
Example
javascript
function showArguments() {
console.log(arguments);
}
showArguments("apple", 42, true);Result in the console:
javascript
[Arguments] { '0': 'apple', '1': 42, '2': true }So arguments is an array-like object:
- indices (
0,1,2, ...) - a
lengthproperty - but no array methods (
map,forEach, etc.)
Accessing arguments
javascript
function sumAll() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sumAll(1, 2, 3, 4)); // 10Here we don't declare parameters,
we just take everything passed via arguments.
Difference from parameters
javascript
function show(a, b) {
console.log(a, b);
console.log(arguments[0], arguments[1]);
}
show("x", "y");
// a,b → "x","y"
// arguments[0], arguments[1] → "x","y"They match as long as you don't change the values.
Changes to arguments and parameters (in regular functions)
javascript
function demo(a) {
console.log(a, arguments[0]); // 10, 10
a = 20;
console.log(a, arguments[0]); // 20, 20
}
demo(10);In regular functions, arguments and parameters are linked - changing one changes the other
(but this does not work in strict mode ('use strict')).
Arrow functions have no arguments
javascript
const arrow = () => {
console.log(arguments); // ReferenceError
};
arrow(1, 2, 3);Why:
- Arrow functions do not create their own
argumentsobject. - If you access it, it is taken from the outer function, if there is one.
The alternative - the rest (...) operator
A modern and safe alternative to arguments - rest parameters:
javascript
function sumAll(...args) {
return args.reduce((sum, n) => sum + n, 0);
}
console.log(sumAll(1, 2, 3)); // 6Advantages of ...args over arguments:
- It's a real array (has
.map,.filter,.reduce). - Works in arrow functions.
- No confusion with "linked" values.
- The code looks cleaner and clearer.
Quick summary
| Property | arguments | ...rest |
|---|---|---|
| Type | Array-like object | Array |
Array methods (map, forEach) | No | Yes |
| Available in arrow functions | No | Yes |
| Linked to parameters | Yes (in non-strict) | No |
| Modern way | Deprecated | Recommended |
Example to remember
javascript
// Old way
function oldSum() {
return Array.from(arguments).reduce((a, b) => a + b);
}
// New way
const newSum = (...nums) => nums.reduce((a, b) => a + b);
console.log(oldSum(1, 2, 3)); // 6
console.log(newSum(1, 2, 3)); // 6Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.