paint-brush
How to Use Rest Parameters in JavaScriptby@micogongob
328 reads
328 reads

How to Use Rest Parameters in JavaScript

by Mico GongobJuly 23rd, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.

Company Mentioned

Mention Thumbnail
featured image - How to Use Rest Parameters in JavaScript
Mico Gongob HackerNoon profile picture

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.