The Spread Operator and Objects

In this lesson, you will use the spread operator on an object.

Simple copy

You can spread an object similar to an array. Spreading an object is handy in a scenario where you need to create a clone for immutability purposes or if you are already using the function Object.assign.

The assign method is similar in functionality but uses a more verbose syntax. The syntax for the spread operator is identical to the spread for an array which means that it uses the three dots in front of the object instead of the array.

To create a clone, you need to define a variable, open a curly bracket, a spread operator, the variable to copy, and close the curly bracket. It copies all members and makes them float side by side with a comma. Indeed, this is just a visualization to help you illustrate that the curly brackets take the result and form a new object.

In the following code, line 2 is performing the object clone. Notice the curly brackets { and } and the use of the spread operator .... The output is false because they are not the same object, they have a different reference in memory. Altering one will not change the other.

Get hands-on with 1400+ tech skills courses.