Trusted answers to developer questions

What is the arguments object in JavaScript?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Arguments

arguments is an object that is accessible inside functions that contain the values of the arguments passed to that function.

function test(a, b, c) {
console.log("Printing arguments: ", arguments[0], arguments[1], arguments[2]);
}
test(1,2,3); //1, 2, 3

The arguments object is only available inside non-arrow functions. Although it isn’t an array, we can access elements using the index, and it has a length property that contains the number of arguments passed to the function.

function test(a, b, c) {
console.log(arguments.length);
}
test(1); // 1
test(1, 2); // 2

The arguments objects contain all of the arguments passed during the function call, even if there are not as many parameters in the function declaration.

function test() {
console.log(arguments.length);
}
test(); //0
test(1); //1
test(1,2,3,5); //4

We can update the value of arguments:

function test(a) {
arguments[0] = 100;
console.log(arguments[0]);
}
test(); //100
test(1); //100

If we change the value of the parameter inside a function without rest, default, or restructured parameters, it will be updated in the arguments object and vice versa.

function test(a, b) {
arguments[0] = 100;
console.log("a=>", a, "arg[0]=>", arguments[0]);
b = 0;
console.log("b=>", b, "arg[1]=>", arguments[1]);
}
test(1, 2);
// a=> 100 arg[0]=> 100
// b=> 0 arg[1]=> 0

But if we use rest, default, or restructured parameters in a function, the synchronization between the arguments and the variables will not happen.

function test(a = 10, b= 20) {
arguments[0] = 100;
console.log("a=>", a, "arg[0]=>", arguments[0]);
b = 0;
console.log("b=>", b, "arg[1]=>", arguments[1]);
}
test(1, 2);
// a=> 1 arg[0]=> 100
// b=> 0 arg[1]=> 2

Properties

length → contains the number of arguments passed to the function

callee → contains the currently executing function reference

function test() {
console.log(arguments.callee);
console.log(arguments.length);
}
test(1,2,3);

RELATED TAGS

javascript
arguments

CONTRIBUTOR

Programming Bytes
Attributions:
  1. undefined by undefined
Did you find this helpful?