How to send a variable number of arguments to a JavaScript function?

Sometimes, we want to send a variable number of arguments to a JavaScript function.

In this article, we’ll look at how to send a variable number of arguments to a JavaScript function.

How to send a variable number of arguments to a JavaScript function?

To send a variable number of arguments to a JavaScript function, we can use the rest syntax.

For instance, we write

const func = (...args) => {
  args.forEach((arg) => console.log(arg));
};

const values = ["a", "b", "c"];
func(...values);
func(1, 2, 3);

to create the func function that takes an unlimited number of arguments with ...args.

All the arguments are in the args array.

In it, we call forEach with a callback to log the args entries.

Then we call func with all the entries in values as arguments with

func(...values);

We can also call it with the arguments written explicitly like

func(1, 2, 3);

Conclusion

To send a variable number of arguments to a JavaScript function, we can use the rest syntax.