Understanding the JavaScript Spread Operator



There’s a good chance that you have probably come across the Javascript spread operator. If you are unsure, here’s what it looks like:

{...}

Good luck trying to google search that as you will probably get an empty results page. The Javascript spread operator is a new syntax found in ES6 (ECMAScript2015). The purpose of the spread operator is to allow an iterable like an array or string to be expanded (or spread) across another object or array.

Cloning Array Using Spread Operator

The most common use of the spread operator is to clone an array. For example, say I do the following:

 var a = ['A', 'B',' C'];

var b =  a;

In pretty much any language, you could easily guess the problem that will occur here. Once you assign variable B to A, B now points to the memory location of A. This means that if you were to change A at some point later in your program, B will also get altered. So the simple way around that is to use the slice command.

 var a = ['A', 'B',' C'];

var b =  a.slice();

This returns a shallow copy of A to B. So now any changes that you make to A will not alter B. An alternative way of doing this is using the Javascript spread operator:

 var a = ['A', 'B',' C'];

var b =  [...a]

Keep in mind, if your array contains objects or other arrays, then you will still need to perform a deep clone.

React and Redux Spread Operator

The most common place that you will encounter the spread operator is when using reactjs and redux. Whenever you update an object, it’s always using the spread syntax:

this.setState({ review: { ...this.state.review, score: event.target.value } });

In the above example, I set the state of the review object to a new object that contains the properties of the existing state object, along with the changed property of score. That’s pretty much all there is to the spread operator. If you want a really in-depth look, check out MDN’s documentation on it. 

Posted in ES6