javaScript arguments object in action

When writing a function in javaScript, inside the body of that function there is an special identifier that can be used to access any and all arguments that have been passed to the function when it is called. This identifier is known as the javaScript arguments object which is an array like object that can be used to find out things like the number of arguments that was given to the function when it was called, alone with the values of course.

1 - javaScript arguments object basic example

For a basic example of the javaScript arguments object here is a simple function that uses this as a way to return a different result depending on the number of arguments that is given when the function is called.

1
2
3
4
5
6
7
8
9
10
11
12
13
var func1 = function (a, b) {
if (arguments.length == 2) {
return a + b;
}
return a;
};
console.log(func1(40,2)); // 42
console.log(func1(42)); // 42

Without using the arguments object to find the number of arguments that is given the function would return NaN when used with just a single argument. So the arguments object is there to help write functions that will work differently depending on the number of arguments that is given.

2 - Why it is the arguments object rather than arguments array

The arguments object is called the arguments object because it is not an instance of an Array. So it is actually just a plain old object, however it can be considered an array like object. This is because although it is not an instance of an Array it is structured like an array, so some Array methods can be used with it via something like Function.call.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let func = function () {
let i = 0;
[].forEach.call(arguments, (n) => {
i += n;
});
return i;
};
console.log( func(1,2,3,4,5)); // 15

3 - The length property

The length property can be used to know the number of arguments that where passed to the function when it was called. This can then be used as a way to have more than one expression that is used for something depending on the number of arguments that are given. For example say I want a method that will just get an element in an array by index if it is given one argument, but will use a more complex expression when given two arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
let mod = {
grid: [1, 2, 3, 4, 5, 6, 7, 8, 9],
w: 3,
get: function (xi, y) {
if (arguments.length < 1) {
return null;
}
if (arguments.length === 1) {
return this.grid[xi];
} else {
return this.grid[y * this.w + xi];
}
}
};
console.log(mod.get(1)); // 2
console.log(mod.get(2,1)); // 6