ES6: The spread syntax — A concise way of applying elements to arrays and functions in JavaScript

In previous post, we started to look at some of the treats introduced in ES6 by looking at destructuring.

In this post we’ll look at another great syntactical additions to JavaScript called the spread syntax.

The spread syntax is quite simple. Say you got some elements in an iterable object — e.g. an array —, and you want to apply the elements it contains to a new array or a function call.

Usually, at this stage you would bring out the indexes and loops to start applying the elements. Luckily, the spread syntax makes this way easier. You simply prefix the iterable object you want to spread with three dots — ....

To make sense of this, let’s see how this actually works by looking at some different use cases.

Copying an array

Say we got an array of names.

const names = ['Luke','Eva','Phil'];  

Now, how could we copy the elements of names to a new array?

In more traditional solutions, this would quickly become a tedious job using imperative approaches like loops. By using the spread syntax, the solution would become much simpler.

const copiedList = [...names]  
console.log(copiedList); // ['Luke','Eva','Phil']  

As you can see, by using the spread syntax we’re able to apply the elements of the old array to a new one in a concise way.

It’s worth mentioning that this is not an immutable operation, because even if you spread the elements to a new array, it’ll still have the same reference. This means that if one of the elements is an object, and you update the content of the object, the content will appear changed in both arrays.

var initialArray = [{name: "Luke"}];  
var copiedArray = [...initialArray];

initialArray[0]['name'] = 'Mark';

console.log(initialArray); //Array [{'name': 'Mark'}]  
console.log(copiedArray); //Array [{'name': 'Mark'}]  

Concatenating arrays

Another great usage of the spread syntax is to concatenate arrays. This is done by simply spreading the elements of the arrays you want to concatenate into the same array.

const concatinated = [...names, ...names];  
console.log(concatinated); // ['Luke','Eva','Phil', 'Luke','Eva','Phil']  

Spreading elements together with an individual element

Beside simply spreading elements into an empty array, you can also spread elements together with other standalone elements.

One example could be to create an array where you first add a simple name, then spread the elements from names at the end.

const first = ['Emily', ...names];  
console.log(first); // ['Emily','Luke','Eva','Phil']  

Another option is to spread the names first, then add another name at the end.

const last = [...names, 'Emily'];  
console.log(last); // ['Luke','Eva','Phil', 'Emily']  

As you can see — you can easily move around the spread syntax to get what you want.

Spreading elements on function calls

Now that we’ve covered how to use the spread syntax in array literals, let’s look at how we can apply the elements to a function call.

Let’s say we got a simple function — printer — that takes three arguments and print them.

const printer = (name1, name2, name3) => {  
    console.log(`Names: ${name1}, ${name2} and ${name3}`);
};

With our printer function defined, let’s use the spread syntax to apply our array of names to the printer function.

printer(...names); // Names: Luke, Eva and Phil  

As with the array literal, we can combine the spreading of the elements with other individual elements.

Let’s add 'Emily' as the first argument to our printer function, followed by ...names.

printer('Emily', ...names); // Names: Emily, Luke and Eva  

If you pass too many arguments to the function, the elements that can’t fit into the parameter list will be omitted.

Bonus: Spread syntax for object literals!

As a bonus, let’s look the spread syntax for object literals.

This is a feature that has been proposed as an addition to ECMAScript. The cool thing however, is that you can use it today using a babel plugin called babel-plugin-transform-object-rest-spread.

What this variant of the spread syntax allows you to do, is to spread properties from one object to another.

Say you got two objects containing information about a person — nameAndAge and about.

const nameAndAge = {  
  name: 'Luke',
  age: 24,
}

const about = {  
  work: 'Developer',
  hobby: 'Skydiving',
}

Next, we want to merge these two into one object using the spread syntax.

const person = {  
  ...nameAndAge,
  ...about,
}

console.log(person);  
//{
//  "age": 24,
//  "hobby": "Skydiving",
//  "name": "Luke",
//  "work": "Developer"
//}

That's it for now. In the next post, we'll continue looking at ES6 additions, so make sure to subscribe!

Enjoyed the post?

If you don't want to miss future posts, make sure to subscribe