JavaScript Three dots (…) Rest Parameters and Spread Syntax

I came across a pair of interesting language features in the newer JavaScript standards based on the three dot notation (…).  This syntax is supported in Chrome, Edge, Firefox and most newer browsers.  When you see three dots in the context of a Javascript function parameter that is known as a Rest Parameter.  For example: function myfunc(…params)  When you see the three dots in the context of a JavaScript function call or variable declaration this is known as the spread syntax.

First some detail on the Rest Parameter feature.  The rest parameter feature basically means ‘any number of parameters goes here’. So lets look at an example:

You can have more than one parameter, but the rest parameter must always be the last parameter of the JavaScript function as in function PlaceOrder(orderDate,…lineItem)

Next some detail on the Spread Syntax.  With Spread Syntax you can expand any array or string. Lets look at an example using some array literals.

And here’s an example of spread syntax in the context of a function call.

The biggest gotcha in learning these two features is understanding that three dots (…) is really two different features, rest parameters when used as a function parameter and spread syntax when used in variable declaration or in calling a function.  These features do provide a nice bit of ‘syntactic sugar’ to JavaScript, using this notation looks clean in the code as opposed to earlier alternatives such as using array methods or writing code to pack or unpack the arrays.  Happy coding.

Rest Parameter

Spread Syntax