Curriculum
Course: React
Login

Curriculum

React

Text lesson

ES6 Spread Operator

Spread Operator

The JavaScript spread operator (...) enables you to quickly copy all or part of an existing array or object into a new array or object.

Example

const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

The spread operator is commonly used alongside destructuring.

Example

Assign the first and second items from numbers to variables, and place the remaining items into a new array.

const numbers = [1, 2, 3, 4, 5, 6];
const [one, two, ...rest] = numbers;

The spread operator can also be used with objects.

Example

Merge these two objects:

const myVehicle = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'red'
}

const updateMyVehicle = {
 type: 'car',
 year: 2021,
  color: 'yellow'
}

const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
The non-matching properties were merged, but the matching color property was overwritten by the last object, updateMyVehicle, resulting in the color being yellow.