How to use the spread operator (...)

Learn how to use the three-dot operator (...) is also known as the spread operator.

spread operator

JavaScript's spread operator (...) can expand an iterable object (such as an array) into more elements.

This allows us to quickly copy all or part of an existing array to another array:

instance

Use the spread operator in JavaScript to merge two arrays

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

try it yourself

The spread operator is often used to extract the required part from an array:

instance

Assign the first and second items of the numbers array to variables, and put the remaining parts into another array:

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

try it yourself

We can also use the spread operator on objects:

instance

const myVehicle = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'red'
{}
const updateMyVehicle = {
  type: 'car',
  year: 2021,
  color: 'yellow'
{}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}

try it yourself

Please note that mismatched properties are merged, but matching properties color the last object passed in updateMyVehicle Covered. The final color is now yellow.

Related Pages

Tutorial:JavaScript ES6