How to take unlimited arguments in JavaScript

Some functions are designed to be very flexible and general-purpose. By allowing an arbitrary number of arguments, a function can adapt to a variety of situations. For example:

  • A function that calculates the sum of any number of numbers.
  • Logging functions that can take multiple arguments to be printed.
  • Function wrappers or decorators to modify the behavior of functions.
  • A function that formats a string with dynamic content.

There are two ways to take unlimited number of arguments in a JavaScript function: one is to use the arguments object, the other is to use the rest parameter syntax.

Using arguments object

The arguments object in JavaScript is an array-like object that is available inside every non-arrow function. It contains the values of the arguments passed to that function. You can use it to access the arguments by their index, or iterate over them with a loop.

function sum() {
  var total = 0;
  for (var i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(4, 5, 6, 7)); // 22

Using rest parameters

The use of the arguments object has some drawbacks and is considered an older style. In modern JavaScript, it’s often better to use rest parameters (...) to gather up remaining arguments into a real array. Rest parameters provide more flexibility and are more readable.

function sum(...nums) {
  var total = 0;
  for (var num of nums) {
    total += num;
  }
  return total;
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(4, 5, 6, 7)); // 22

Rest parameters also come with the benefits of being a real array and are easier to work with compared to the arguments object, which is array-like but not a true array.