JavaScript ES6 Rest and Spread Operator

Wednesday, November 11, 2015

Working with arrays and parameters have become a bit easier now that spread and rest parameters have been released as a part of the ECMAScript 6 upgrade.

The syntax for these operators are the same (...) with the difference being:

  • The rest operator will collect the parameters into an array
  • The spread will take an array and move them into parameters when used when calling a function.

The Rest Operator

So in this example, the function will take the parameters on the end of the call and add them together:

In the example above, the "amounts" is a rest parameter because it has the (...) in front of it. This tells the function to expect a list of parameters to come in and combine them into an array. If the call does not contain any amounts then the amounts variable will equal an empty an array.

When you are using the rest operator, there can only be one per function placed at the end of the function signature.  Also, when you use a rest operator, the "arguments" object in that function can no longer be used.

The Spread Operator

As stated before, the spread operator has the same syntax as the rest operator but works in reverse. Instead of passing one to many parameters in the function call, you pass and array designated with the (...) and it get spread out over the parameters in the method signature.

In the above code, if the array is bigger than the amount of parameters, then the array fills in the parameters until there are no more parameters in the function signature. The rest of the items in the array are ignored.

One way the spread makes working with arrays so much nicer, is the ability to use the spread operator to combine arrays.

You can also use the spread operator to "push" an array on to another array instead of just a single a value or an object.

Summary

These operators not only give syntactical sugar when working with arrays, but I am noticing developers in the JavaScript community taking these operators and using them in ways that makes their code more decoupled. A specific object does not need to be passed to a function anymore. A function could take an array of values or a function call could spread values over a list of parameters.

I think it's a great addition to the language.

comments powered by Disqus