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
let someArguments = ['hi','bye']; function logArgs (arg1, arg2) { return console.log(`${arg1} ${arg2}`); } logArgs(...someArguments); //hi bye
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:
logArgs(someArguments[0], someArguments[1]); //hi bye
But now, you just use the spread operator and it’s like doing exactly what I did above, but faster.
Array Literals
let arr = [1,2,3]; console.log([...arr,4,5]); // [1,2,3,4,5]
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:
let oldState = [1,2,3]; let newState = [...oldState,4]; console.log(oldState); // [1,2,3] console.log(newState); // [1,2,3,4]
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:
let newObject = {...someObject, aProperty: true}
You can start using this if you use babel.
In ES6, the above code can be accomplished with the new Object.assign function:
let someObject = {aProperty: true, anotherProperty: true} let newObject = Object.assign({}, someObject, {aThirdProperty: true}) console.log(someObject); console.log(newObject);
You mantain the old object intact, and quickly create a new one with an additional property.
Leave a Reply