Hackernoon logoHow to Use Rest Parameters in JavaScript by@micogongob

How to Use Rest Parameters in JavaScript

This short article will cover Rest parameters and how to use them in JavaScript programming. The arguments object is an accessible object that contains the values of the parameters passed to a function. Rest parameters allow you to use an indefinite number of parameters as an array (not an object) Rest parameters are an alternative to the arguments object. The rest parameters' syntax allows you to basically capture the rest of the. parameters. It is not an array so you can’t perform things like.slice() with it.
image
Mico Gongob Hacker Noon profile picture

@micogongobMico Gongob

PH Software Engineer

This short article will cover Rest parameters and how to use them in JavaScript programming. I assume you have some familiarity with coding in the JavaScript ecosystem.

The arguments object

If you have some JavaScript experience, you might be familiar with the arguments object. The arguments object is an accessible object that contains the values of the parameters passed to a function.

function func1(a, b, c) {
  console.log(arguments[0]);
  // expected output: 1

  console.log(arguments[1]);
  // expected output: 2

  console.log(arguments[2]);
  // expected output: 3
}

func1(1, 2, 3);

However, there are limits with the arguments object. The first is that it is not an array so you can’t perform things like 

slice()
 with it. The second issue is there is no direct way to access a specific subset of the function parameters.

Rest parameters

If the arguments object is not fit with your use case, you can use the new rest parameters where you use it with the …syntax. It allows you to basically capture the rest of the parameters. What that means is your functions can accept an indefinite number of parameters as an array (not an object).

In the code example below, we used the rest parameters' syntax for the second parameter. That means we can have a different variable for the first parameter, which is a capability not present with the arguments object.

function log(level, ...args) {
  for (var i = 0; i < args.length; i++) {
    console.log(level + ': ' + args[i]);
  }
}

log('INFO', 'Hello There', 6, 'I have the high ground', 'It\'s a trap');

// expected output:
// INFO: Hello There
// INFO: 6
// INFO: I have the high ground
// INFO: It's a trap

That is all. We learned about how we can use rest parameters as an alternative to the arguments object.

Originally published at https://micogongob.com/rest-parameters-in-javascript.

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.