The rest and spread operator in ES6
August 12, 2017 Leave a comment
ES6 comes with a new operator that consists of three dots: … It is strongly related to arrays. It has two major purposes:
- It allows a function to have an arbitrary number of parameters of a certain type. This is the same as a parameters array in a C# or a Java function with varargs
- Join arrays in an elegant way
Let’s see how the … operator works.
Parameters to a function
Consider the following function:
function buildTeam(...members) { return members.reduce((latest, member) => { latest.push(member) return latest }, []) }
The buildTeam accepts a parameter called members. It is modified with the new … operator. The parameter will be treated as an array in the function body. Therefore we can use all the new ES6 array helper functions on it. In this case we call the reduce function and collect all the incoming names into an array and return it.
Here’s how we can call the buildTeam function:
let allMembers = buildTeam('John', 'Mary', 'Jane', 'Bill')
allMembers will be…
["John","Mary","Jane","Bill"]
Note how we can call buildTeam with an arbitrary number of string arguments. They will be organised into an array behind the scenes when buildTeam is called.
Joining arrays
Say that we have organised various programming languages into the following categories:
let strictOopLanguages = ['C#', 'Java', 'C++'] let looseOopLanguages = ['Python', 'Ruby'] let funcLanguages = ['F#', 'Scala', 'Erlang'] let frontEndLanguages = ['JavaScript', 'HTML', 'CSS']
Now we want to build an array which includes all of them. The … spread operator can help us to easily achieve that:
let allLanguages = [...strictOopLanguages, ...looseOopLanguages, ...funcLanguages, ...frontEndLanguages]
allLanguages will include all array elements:
["C#","Java","C++","Python","Ruby","F#","Scala","Erlang","JavaScript","HTML","CSS"]
We can mix the spread operator with the “normal” way of adding elements to an array. What if we want to add a language in allLanguages which doesn’t have a matching category? Easy:
let allLanguages = ['SQL', 'Lua', ...strictOopLanguages, ...looseOopLanguages, ...funcLanguages, ...frontEndLanguages]
View all posts related to JavaScript here.