JavaScript: The Spread Operator

JavaScript: The Spread Operator

The spread operator is awesome. It can do SO much — it’s efficient, readable, and can save a whole load of mess. I don’t know how you can not love it!

It’s a reasonably new feature of JavaScript that came with ECMA2015 (or ES6, if you prefer, although the former is technically correct!) — or for those unfamiliar with these terms — a recent standard update of JavaScript.

So, What is the Spread Operator?

Three dots: …

Three very powerful dots, that allow you to expand arrays or iterable objects in places where array elements or key-value pairs would be expected.

There’s three such places: functions calls, elements in arrays, and key-value pairs in objects.

Let’s breathe a bit of life into those words and have a look at what this thing can do!

The Spread Operator in Arrays

Let’s say we’ve got an array letters which we want to insert into a new array:

We can just…

var letters = [‘c’, ‘d’];
var newLetters = [‘a’, ‘b’, ...letters, ‘e’];
// newLetters is [‘a’, ‘b’, ‘c’, ‘d’, ‘e’];

When you see the spread operator in an array, it’s just expanding one array into another.

Manipulating Arrays with the Spread Operator There’s a few things you can do with spread syntax to manipulate arrays. I’ll include a couple of examples to show you what it can do!

Adding values to arrays

var smallNums = [1, 2, 3];
var bigNums = [4, 5, 6];
smallNums.push(...bigNums);
// smallNums is [1, 2, 3, 4, 5, 6];

Self explanatory — and beautiful. Using the spread operator allows you to turn smallNums into a flat array (rather than a nested array, which would be the result without spread syntax).

Concatenating arrays

As an alternative to .concat(), you can:

var smallNums = [1, 2, 3];
var bigNums = [4, 5, 6];
nums = [...smallNums, ...bigNums];
// nums is[1, 2, 3, 4, 5, 6];

Be warned though, if performance is important to you, this may not be the best choice as it actually runs a fair bit slower than .concat() — but it is still great to be aware of it because it’s really readable and tidy!

Another way to split strings

I don’t have anything against String.prototype.split() — but the spread operator’s way of doing it is pretty cool, and the kind of thing a nifty JS developer should know! Check this out:

var myName = 'Ruth';
var lettersOfName = [...myName];
// lettersOfName = [‘R’, ‘u’, ‘t’, ‘h’];

Copying arrays

If you’re anything like me, you shallowly clone arrays all the time. Do you do it like this?

myArray = [1, 2, 3];
copiedArray = myArray.slice();
// copiedArray is [1, 2, 3];

Yeah, so did I for a while! But then I discovered that you can actually just use the spread operator to make life easier…

copiedArray = [...myArray];
// copiedArray is [1, 2, 3];

This is absolutely great for complex applications where you’re managing immutable state, such as Redux or Vuex.

Function Calls

Let’s say we have a function which takes a bunch of strings as arguments and concatenates them:

var dims = [3, 2, 5];
function calculateVolume (l, h, d) { 
    return l * h * d;
}

Usually you’d need to pass in the arguments one by one, like this:

calculateVolume(dims[0], dims[1], dims[2]);
// 30

Using the spread operator, you can tidy this invocation up nicely:

calculateVolume(...dims);
// 30

The Future: Spread Syntax and Object Literals

Spread syntax for objects is a Stage 3 proposal for ECMAscript (at the time of writing).

Copying objects

Just as with shallowly cloning arrays, I also shallowly clone objects regularly. Until recently, the go-to method was Object.assign():

var myObj1 = {color: 'Purple', likesMarmite: true};
var clonedObj = Object.assign({}, myObj1);
// {color: 'Purple', likesMarmite: true}

I’ve always liked Object.assign() well enough, but the spread operator does the job with far more grace:

var clonedObj = { ...obj1 };
// {color: 'Purple', likesMarmite: true}

Combining objects

Merging objects also becomes neater with the spread operator, an operation traditionally performed with Object.assign().

var myObj1 = {color: 'Purple', likesMarmite: true};
var myObj2 = {color: 'Green', siblings: 3};
var combinedObj = Object.assign({}, myObj1, myObj2);
// {color: 'Green', likesMarmite: true, siblings: 3}

Compare with the spread syntax way of doing things:

var combinedObj = { ...obj1, ...obj2 };
// {color: 'Green', likesMarmite: true, siblings: 3}

This is all pretty similar to cloning and merging with arrays, but it’s fabulous that we’ll be able to do this with objects too!

Don’t Get Confused!

Beware — if you see … in code, it’s not necessarily the spread operator. It could also be the rest parameters.

Rest parameters create functions which can accept any number of arguments. You’ll be able to recognise them easily because they are always found within (and at the end of) function parameters. Here’s an example, just so you can recognise them:

function add (a, ...b) {
    console.log(a);
    console.log(b);
}
add(1, 2, 3, 4);
// 1
// [2, 3, 4]

I’ll do another blog post on Rest Parameters — watch this space!

Is your goal to become a pro developer? Become a Software Developer in as few as 12 weeks at Northcoders, the Coding Bootcamp for the North!

Get all my latest content on Twitter at @RuthYMNg!

Keep coding! 🚀


First published online at https://blog.northcoders.com/javascript-the-spread-operator

Ruth Ng - Software Engineer & Digital Marketer in ManchesterRuth Ng
Software Engineer | Growth Hacker | Digital Marketer