JS: Arrays
Theory: Spread syntax and creating new arrays
Along with the rest syntax, there's another one, the spread syntax. Spread has the same syntax, but performs the opposite task. It doesn't collapse elements, but instead expands them. It's usually used to copy or merge arrays.
Imagine we need to define an array by adding elements from another array. This task is often encountered when working with default values:
... in this case is the spread. It unpacks the array by adding all its elements to the new array. How do you distinguish it from the rest parameter? It's all about when it's used. The rest parameter appears to the left of the equal sign, where the destructuring happens. The spread goes to the right of the equal sign, where the array is formed.
A spread, unlike a rest parameter, can appear in any part of an array. For example, we can add to the original array on the left instead of the right:
And even in the middle:
The spread works with any number of arrays:
Copying an array
Spread syntax is often used to copy an array. Copying prevents you from changing the original array when you need to change a copy of it:
Recommended programs
Completed
0 / 22

