DEV Community

byby
byby

Posted on • Originally published at byby.dev

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
efpage profile image
Eckehard • Edited

There are a lot of cool things you can do with rest parameters. These patterns can be helpful:

function test(a=10, ...restPar){  // combine normal and rest parameters
    const [b=20,c=30, d=40] = restPar // destrucuting with defaults
    console.log(a) // --> Hello
    console.log(b) // --> World
    console.log(c) // --> 30
    console.log(d) // --> 40
}

test("Hello","World")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
john73cloud profile image
john73-cloud

Are there any performance benefits with using either one

Some comments may only be visible to logged-in visitors. Sign in to view all comments.