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); // 1test(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(); //0test(1); //1test(1,2,3,5); //4
We can update the value of arguments:
function test(a) {arguments[0] = 100;console.log(arguments[0]);}test(); //100test(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
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);