Object Spread Operator

The object spread operator is something I find myself using all of the time these days.

First of all, it can be used to copy an object:

const o1 = {x:10, y:10, z:10};
const o2 = {...o1};
console.log(o2); //{x:10, y:10, z:5}

o2 is now an exact copy of o1 (a shallow copy).

If you want a copy of an object, but with one property changed, you can do this:

const o1 = {x:10, y:10, z:10};
const o2 = {...o1, z:5};
console.log(o2); //{x:10, y:10, z:5}

Or, with two properties changed:

const o1 = {x:10, y:10, z:10};
const o2 = {...o1, y:5, z:5};
console.log(o2); //{x:10, y:5, z:5}

This is useful when you want to use a more functional style of programming, which is becoming popular in the React community. In functional programming we don’t mutate data. Instead, you make a copy with the changes you want.

So instead of this:

o1.z = 5;

which mutates o1. We can do this

const o2 = {...o1, z:5};

which returns a new object (a copy) with one property updated.

The reason it’s called the spread operator is that it converts this:

{x:10,y:10,z:10}

to this:

x:10,y:10,z:10  //without the curly braces

Thus the following expression:

{...o1, z:5}

is equivalent to this expression:

{x:10,y:10,z:10, z:5}

As you can see, it takes the o1 object and spreads it out.

By the way, you may have noticed the above object has z twice. In JavaScript when this happens, the last z wins. So end result is really just this:

{x:10,y:10,z:5}

A Common Use-Case

I tend to do a lot of my css in JavaScript. This is a great use-case for the object spread operator:

const style = {
color: "black",
background: "grey",
padding: "1rem"
}
const styleSelected = {
...style,
color: "blue"
}
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.