Three dots in Javascript: How to use the Spread Operator and its use with Immutable Arrays

What are the three dots you see in javascript code snippets? The three dots are called the spread operator. It’s a new feature brought in with ES6. ¬†In this post I will show you some examples where you can use it. I will then talk about how they are helpful for Immutability in your code.

The spread operator allows you to expand an expression in places where you would expect multiple arguments (in functions) or multiple elements (in arrays).

Function Calls

The spead operator can be used for function calls. Say you have a function like the above one where you take in 2 arguments and return them together in a string. To pass in the arguments, you would need to pass them one by one like:

But now, you just use the spread operator and it’s like doing exactly what I did above, but faster.

Array Literals

Here’s a better use IMO for the spread operator: array literals. The example is self explanatory. Say you have an array with 1, 2, 3 as elements. When you use the spread operator inside an array, it’s expanding another array into it.

The Case for Immutable Arrays

Imagine you have a complex application where you have to manage state. It is better for your state to be an immutable object and it will probably contain an array in it.

So how do you handle immutable arrays with the spread operator? Lets look at a simple example:

Imagine you have a state which is an array of 3 elements, and your new state after some action has 4 elements in the array. Your first thought would be to do oldState.push(4) to just push a new element into the array.

The problem with this is that you are mutating your state, which makes it impossible to know what the previous state was later on. So by using the spread operator, you can quickly create a new array based on the old one.

Spread Operator for Objects

There is a proposal for the next version of Javascript (ES7 I believe) to include an object spread operator. This will make it easy to create new objects based on existing ones and also to override properties:

You can start using this if you use babel.

In ES6, the above code can be accomplished with the new Object.assign function:

You mantain the old object intact, and quickly create a new one with an additional property.

Author: JP

Javascript jedi padawan.