bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch
Learn/React/React Core Practice
React•React Core Practice

React ES6 Spread Operator

Spread Operator

The JavaScript spread operator (... ) allows us to quickly copy all or part of an existing array or object into another array or object.

Example

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

The spread operator is often used in combination with destructuring.

Example

Assign the first and second items from numbers to variables and put the rest in an array:

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

We can use the spread operator with objects too:

Example

Combine these two objects:

const car = {
brand: 'Ford', model: 'Mustang', color: 'red'
}
const car_more = {
type: 'car', year: 2021, color: 'yellow'
}
const mycar = {...car, ...car_more}

Notice that the properties that did not match were added, and the property that did match was overwritten by the last object.

Previous

JavaScript Array map()

Next

React ES6 Ternary Operator