The rest and spread operator in ES6

ES6 comes with a new operator that consists of three dots: … It is strongly related to arrays. It has two major purposes:

Let’s see how the … operator works.

Parameters to a function

Consider the following function:

function buildTeam(...members) {
  return members.reduce((latest, 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…


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:


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.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: