How to Pass a Variable Number of Arguments into a Function in JavaScript
What if we want our JavaScript functions to take a dynamic, or variable, number of arguments?
Using arguments
We could access the arguments
variable that’s accessible inside every JavaScript function.
function variableArguments() {
console.log(arguments);
}
variableArguments(1, 2, 3); // Arguments(3) [1, 2, 3, ...]
This issue with this is that there are zero parameters to this function, which make it unclear whether we should pass in any.
Another issue that this arguments
variable is not accessible inside arrow functions.
const variableArguments = () => {
console.log(arguments);
};
variableArguments(1, 2, 3); // Error: arguments is not defined
Using the spread operator
What we can do is use the spread operator.
By using the spread operator as a parameter, we are allowing any number of arguments be accessed by this args
variable.
function variableArguments(...args) {
console.log(...args);
}
It even works with arrow functions.
const variableArguments = (...args) => {
console.log(...args);
};
And TypeScript :)
const variableArguments = (...args: any[]) => {
console.log(...args);
};