Start your developer blog today!
Email me

How to Pass a Variable Number of Arguments into a Function in JavaScript

Apr 1, 2021 1 min read

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() {
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 = () => {
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 opreator as a parameter, we are allowing any number of arguments be accessed by this args variable.

function variableArguments(...args) {

It even works with arrow functions.

const variableArguments = (...args) => {

And TypeScript :)

const variableArguments = (...args: any[]) => {

More JavaScript Articles