Use the Spread Operator to Update Objects

02/02/20191 Min Read — In JavaScript

In the past, Javascript only had objects but no maps. Objects were both used as records and as dictionaries.

(From JavaScript for impatient programmers (beta) by Axel Rauschmeyer):

Records: Objects-as-records have a fixed number of properties, whose keys are known at development time. Their values can have different types. [...]

Dictionaries: Objects-as-dictionaries have a variable number of properties, whose keys are not known at development time. All of their values have the same type. It is usually better to use Maps as dictionaries than objects [...].

Often, object literals define the state of your program (Objects-as-records).

And state is one of the mutable parts of your program. So, you will change it

You can use a handy trick to change object properties with Object Rest/Spread Properties for ECMAScript.

(From JavaScript for impatient programmers (beta):

With spreading, you can change a property non-destructively: You make a copy of the object where the property has a different value.

For example, this code non-destructively updates property .foo:

const obj = { foo: "a", bar: "b" };
const updatedObj = { ...obj, foo: 1 };
assert.deepEqual(updatedObj, { foo: 1, bar: "b" });

This is useful when you pass objects to other functions that update state.

In React, state is also a plain Javascript object. But remember that React has a setState() method which is responsible for managing and scheduling updates to state.
You can read more about React's state and immutability in this medium post.

If you use Redux, you can swap the object spread syntax for the commonplace Object.assign(). With Redux, you don't mutate change but create copies of objects with new or updated values.