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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function myFunc(...params) { for(let parm in params) { console.log(params[parm]); } } myFunc('a','b','c','d'); //output: //a //b //c //d |
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.
1 2 3 4 5 |
let quarter1 = ['January','February','March']; let quarter2 = ['April', 'May', 'June']; let firstHalf = [...quarter1, ...quarter2]; console.log(firstHalf); // output = [ 'January', 'February', 'March', 'April', 'May', 'June' ] |
And here’s an example of spread syntax in the context of a function call.
1 2 3 4 5 6 7 8 9 10 11 12 |
function sum(...params) { let sum = 0; for(let i = 0; i < params.length; i++){ sum += params[i]; } return sum; } let myArrayOfIntegers = [1,2,3,4,5]; console.log(sum(...myArrayOfIntegers)); //Output: 15 |
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.