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:
const frenchCities = ['paris', 'marseille'];
const cities = ['milan', 'rome', ...frenchCities];
// ['milan', 'rome', 'paris', 'marseille']
// The frenchCities array does not change in any way
// The same without the spread
const cities = ['milan', 'rome'].concat(frenchCities);
...
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:
const cities = [...frenchCities, 'milan', 'rome'];
// ['paris', 'marseille', 'milan', 'rome']
// Without a spread
const cities = frenchCities.concat(['milan', 'rome']);
And even in the middle:
const cities = ['milan', ...frenchCities, 'rome'];
// ['milan', 'paris', 'marseille', 'rome']
// Without a spread, this kind of code cannot be expressed by a single operation
The spread works with any number of arrays:
const frenchCities = ['paris', 'marseille'];
const italianCities = ['rome', 'milan'];
// merging two arrays
const cities = [...frenchCities, ...italianCities];
// ['paris', 'marseille', 'rome', 'milan']
// Without a spread
const cities = frenchCities.concat(italianCities);
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:
const frenchCities = ['paris', 'marseille'];
const copy = [...frenchCities];
copy.push('lyon');
console.log(copy); // => ['paris', 'marseille', 'lyon']
console.log(frenchCities); // => ['paris', 'marseille']
// Without a spread
const frenchCities = ['paris', 'marseille'];
const copy = frenchCities.slice();
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.