The JavaScript spread operator (...
) allows you to quickly and easily copy all or part of an existing array or object into a new array or object.
Using the Spread Operator with Arrays
Combining Arrays
One common use of the spread operator is to combine arrays, In this example, the combinedSet
array contains all the elements from firstSet
and secondSet
.:
const firstSet = [1, 2, 3]; const secondSet = [4, 5, 6]; const combinedSet = [...firstSet, ...secondSet];
Destructuring with the Spread Operator
The spread operator is often used alongside destructuring to assign elements from an array to variables and collect the remaining elements in a new array:
Example
In this case, first
and second
will be assigned the first two values from the numbers
array, while others
will contain the rest of the elements.
const numbers = [10, 20, 30, 40, 50, 60]; const [first, second, ...others] = numbers;
Using the Spread Operator with Objects
The spread operator can also be used with objects to create a new object that includes properties from existing objects:
Combining Objects
Here’s an example of combining two objects, In this example, updatedCarDetails
is a new object that merges carDetails
and additionalDetails
. Notice that the color
property from additionalDetails
overwrites the color
property in carDetails
.:
const carDetails = { brand: 'Toyota', model: 'Corolla', color: 'blue' }; const additionalDetails = { type: 'sedan', year: 2022, color: 'green' }; const updatedCarDetails = {...carDetails, ...additionalDetails};