Rest parameters

While taking a look at what’s new in JavaScript 6, I’ve noticed that it introduces the notion of rest parameters. As we all know, we can pass any number of parameters to a function during its invocation. Until now, if we needed to write a function which receives an undefined number of parameters, we could simply use the arguments object from within it to access all the argument values.

With JavaScript 6, we now have the concept of rest parameters. We can use rest parameters to replace the arguments object in several scenarios. Here’s an example of its usage:

function doSomething(first, …items){
  //access first parameter by name
  console.log(first);
  //access remaining parameters through rest parameter
  items.forEach( item => console.log(item) );
}
//here’s an example of calling the function
doSomething(1, 2, 3);

items is a rest parameters. Rest parameters are indicated by 3 dots (…) and must always be the last parameter specified in the function’s parameter list. The name used for the rest parameter (in the previous example, items) allows us to reference an array which contains the values passed to the function. Notice that unlike arguments, the array referenced by the rest parameter contains only the values passed from the position occupied by the parameter in the function signature (in this case, that means it will contain values from the second position onward – if we need to access the first parameter, then we must use the parameter named first).

Before going on, I must say that you can still use the arguments parameter in JavaScript 6 code. So, why bother using rest parameters? Well, if you have some experience in writing JavaScript, you’ve probably noticed the use of the forEach method for iterating though all the values from the second position onward. This method can only be applied to array instances (for now, let’s forget that we’re using a lambda expression to define the callback function expected by the forEach method). If you decide to go with the arguments parameter, you won’t be able to do that because arguments is an object and not a real array. This might be a good enough reason for using the new rest parameters…

One final note, which might be important for deciding between using rest parameters and the arguments object: the arguments object has additional properties which aren’t related with the values passed as arguments (ex.: callee property).

And that’s it for now. Stay tuned for more.

Advertisements

~ by Luis Abreu on November 26, 2014.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: