In order to get a function’s arguments in JavaScript, we use the arguments
keyword. arguments
is an object that acts like an array. It contains the argument values that are passed to a function.
console.log(typeof(arguments)); //object
Since arguments
is not an actual array, you cannot use methods like forEach()
or map()
. arguments
is available to be used on functions which are not arrow functions (e.g. (x) => `Hello ${x}`;
), although length
is available. If you want to use arrow functions, you can list the values of a function’s arguments using the rest operator in the following manner:
const x = (...args) => {
console.log(args); //[1, 2, 3]
}
x(1,2,3);
You can use the arguments
keyword along with the index in order to extract a function’s arguments:
arguments[0] //A function's first argument
arguments[1] //A function's second argument
arguments[2] //A function's third argument
Using ES5 syntax with the example above, we can extract the arguments in the following manner:
function x (a,b,c){
console.log(arguments[0]); //1
console.log(arguments[1]); //2
console.log(arguments[2]); //3
}
x(1,2,3);
You can also set a function’s argument or modify it like so:
arguments[2] = 'value'
function x (a,b,c){
console.log(arguments[0]); //1
console.log(arguments[1]); //2
arguments[2] = 4;
console.log(arguments[2]); //4
}
x(1,2,3);
We can find out the number of arguments by using arguments.length
:
function x (a,b,c){
console.log(arguments.length); //3
}
x(1,2,3);