How to use the spread operator (...)
- Previous page JS numerical array sorting
- Next page JS scroll to view
Learn how to use the ellipsis 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];
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 part into another array:
const numbers = [1, 2, 3, 4, 5, 6]; const [one, two, ...rest] = numbers;
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}
Please note that unmatched properties are merged, but matching properties color
by the last object passed updateMyVehicle
Covered. The final color is now yellow.
Related pages
Tutorial:JavaScript ES6
- Previous page JS numerical array sorting
- Next page JS scroll to view