Passing Arguments Using Spread

The spread (...) syntax in javascript allows an iterable (array, strings, or object literals) to expand in places where zero or more arguments are expected.

Let’s see a quick example of what exactly is meant by this. In the below example we have two arrays that we combine. One using spread and one not:

const foo = [1, 2, 3];
const bar = [4, 5, 6];

const fooAndBar = [foo, bar]
const fooSpreadBar = [...foo, ...bar]

console.log(fooAndBar);
> [[1, 2, 3], [4, 5, 6]]
console.log(fooSpreadBar);
> [1, 2, 3, 4, 5, 6]

We can see the difference in that using the spread syntax it expands the array so when we combine the arrays they do not become nested because the array itself is unpacked.

A handy usage of this can be seen when copying arrays. Using the spread syntax makes a shallow copy of the array.

const abc = ['a', 'b', 'c'];

// abcCopy is now a shallow copy of the abc array
const abcCopy = [...abc];

The spread syntax also allows you to more easily concatenate an array.

const foo = [0, 1, 2];
const bar = [3, 4, 5];

// previously we had to use concat
foo = foo.concat(bar);
> [0, 1, 2, 3, 4, 5]

// using spread is a bit cleaner
foo = [...foo, ...bar];
> [0, 1, 2, 3, 4, 5]

Read more about it here

Instagram Post