The arguments object
Learn the legacy arguments object you often see in old code and why rest is preferred.
The arguments object
In old JavaScript code you will see an object named arguments. It holds all arguments passed to the function and is available even without parameters. Today the rest parameter is preferred, but you must recognize arguments when reading old code.
Example: function add() { return arguments[0] + arguments[1]; }. Here arguments[0] is the first argument and arguments[1] the second. The call add(3, 5) returns 8.
Rest is preferred
The arguments object is array-like but not a real array. So array methods like forEach, map and filter do not work on it. Also, arrow functions do not have arguments.
For these reasons modern code prefers a rest parameter like ...nums. Rest gives a real array, all array methods work, and it works in arrow functions too. When writing new code, always use rest.
Exercise Sum the first two arguments
Define a function called add. Do not write any parameters. Inside, use the arguments object to return the sum of the first two arguments with return arguments[0] + arguments[1]. Then print the result with console.log(add(3, 5)).
Show example solution
function add() {
return arguments[0] + arguments[1];
}
console.log(add(3, 5));
Test yourself
-
Which is true about the arguments object?
function add() { return arguments[0] + arguments[1]; }- It is not a real array
- It only exists in arrow functions
- It was added in ES2023
- It is more modern than the rest parameter
Show answer
It is not a real array — Correct. arguments is array-like but not a real array; array methods do not work.
-
Access the first argument
function add() { return ____ + arguments[1]; } console.log(add(3, 5));Show answer
function add() { return arguments[0] + arguments[1]; } console.log(add(3, 5)); -
arguments and rest
- arguments
- Not an array, array-like
- ...nums
- A real array
- arguments.length
- Number of arguments
- nums.forEach
- Array method works