6.8 The Spread Operator
The previous video showed how to combine two arrays with the concat method. ES6 introduces an even cleaner way to do the same thing: the spread operator. The syntax is just three dots ... placed in front of an iterable.
const first = [1, 2, 3];
const second = [4, 5, 6];
const combined = [...first, ...second];
// equivalent to [1, 2, 3, 4, 5, 6]
When we spread an array, every element is expanded one by one inside the surrounding literal. We are simply declaring a new array literal that contains all the elements of the first array, then all the elements of the second.
Why spread is better than concat
- It is more visual — you literally see the contents of each array being combined.
- You can mix in extra elements:
[...first, 10, ...second, "x"]is trivial. - It also works to clone an array:
const copy = [...combined];. - The same operator works on objects:
{ ...obj1, ...obj2 }.
const withInBetween = [...first, 10, ...second];
const copy = [...combined];
Doing all of that with concat would be much harder to read. The spread operator is one of the most useful additions of ES6 — you'll meet it constantly in modern code. See you in the next video.
Summary
This lesson explains how to use the JavaScript spread operator (...) to combine arrays in a cleaner, more flexible way than the concat() method. The operator extracts individual elements from one or more arrays and spreads them into a new array. The video also demonstrates how the spread operator can be used to copy arrays and easily insert elements between combined arrays.
Key points
- The spread operator (...) takes all elements from an array and spreads them individually into a new array context
- Combining arrays with spread syntax is more readable and flexible than using the concat() method
- You can insert additional elements between spread arrays using syntax like [...first, newElement, ...second]
- The spread operator can copy an array entirely, serving as an alternative to array.slice() without arguments
FAQ
What is the spread operator in JavaScript?
The spread operator (...) extracts individual elements from an array and spreads them individually. When used in array literals like [...array1, ...array2], each element from the source arrays is placed individually in the new array.
How is the spread operator better than concat() for combining arrays?
The spread operator provides clearer visualization of how arrays are being combined and offers greater flexibility. You can easily insert elements between arrays using syntax like [...first, newElement, ...second], which would require multiple concat() calls to achieve the same result.
Can the spread operator copy an array?
Yes. Using [...array] creates a copy of an array, spreading all elements into a new array. This is functionally equivalent to using array.slice() without arguments.