How to Write a Function that Accepts Any Number of Arguments in JavaScript

There is no function parameter limit, so you can call a function and pass in any number of arguments, regardless of what the function declaration specifies.

There are two ways that can make it possible to create a function with any number of arguments specified.

arguments object

The arguments is an Array-like object, and accessible inside functions that contain the values of the arguments passed to that function.

Let's create a function that accepts N number of parameters in ES5:

function func() {
  console.log(arguments);
  let sum = 0
  for (let i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }
  console.log(sum)
  return sum;
}
func(3, 4, 7); // 14
func(3, 4, 7, 10, 20); // 44
func(3, 4, 4, 8); // 19

Rest Parameters

The rest parameter also can perform an indefinite number of arguments. Use the rest parameter, which has the same syntax as the spread operator to pass an indefinite number of parameters to the specified function:

function add(...args) {
  return args.reduce(function (acc, cur) {
    return acc + cur;
  })
}
console.log(add(3, 4, 8)); // 15
console.log(add(3, 4, 8, 10, 20)); // 45
console.log(add(3, 4, 4, 9)); // 20

The difference between the arguments and the rest parameters is that all array methods can be applied directly on the rest parameters but not on the arguments. The arguments is an Array-like object accessible inside functions containing the values of the arguments passed to that function. The rest parameter syntax allows adding an indefinite number of arguments as an array.

Do you find this helpful?

Related articles