Course Content
JavaScript Data Structures
JavaScript Data Structures
Spread Operator
The spread operator, denoted by ...
, is a helpful tool for creating new objects by merging and copying properties from existing objects. With the spread operator, we can perform the following tasks:
- Clone objects;
- Add or modify properties;
- Create new objects.
Let's focus on how to use the spread operator with objects.
Spread Operator
The spread operator (...
) can be used in various contexts, but one of its most common uses is for creating new objects by spreading the properties of existing objects.
Here's the basic syntax of the spread operator used for object creation:
newObject
: The new object we want to create;sourceObject
: The source object whose properties we want to copy.
Cloning an Object
Let's consider how to clone an object. We will create a new object with the same properties and values as the source object. Any changes made to the new object do not affect the original object.
In this example, clonedObject
is a new object that is clone of originalObject
. Any changes made to clonedObject
will not impact originalObject
. That is why clonedObject
has three properties and originalObject
has only two.
Adding or Modifying Properties
The spread operator is also useful for adding or modifying properties in a new object. We can include additional properties or override existing ones in the new object.
In this example, extendedWaterBottle
is created by spreading the properties of the waterBottle
. Additionally, the color
property is added, and the capacity
property is overridden.
Merging Objects
The spread operator can be used to merge the properties of multiple objects into a single new object. This is especially useful when you have multiple sources of data to combine.
In this example, apartment
is created by merging the properties from apartmentFeatures
and apartmentDetails
.
Thanks for your feedback!