JavaScript Pills: spread operator and rest parameter

Lari Maza
Lari Maza | En
Published in
2 min readNov 22, 2019
Photo by The Creative Exchange

[clique aqui para português]

This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!

Among the numerous new features of ES6 is a new and useful operator. The spread operator, represented by the three-dot ellipsis ..., allows you to distribute the content of any iterable object into multiple elements.

For starters, a simple way to test this operator’s behavior is to use it just before a variable and log the result into the console. Let’s apply it to an array:

const names = ['Lestat', 'Marius', 'Akasha'];console.log(...names);
// Lestat Marius Akasha

Note that the array has been separated, or spread, element by element.

The utilities of the spread operator in practice are broad. One of them is the possibility of combining arrays. See the example below:

const males = ['Lestat', 'Louis', 'Marius'];
const females = ['Pandora', 'Akasha'];
const characters = [...males, ... females];console.log(characters);
// ['Lestat', 'Louis', 'Marius', 'Pandora', 'Akasha']

The end result stored in the variable characters is an array that combines the values ​​of the arrays males and females.

There is also a variation of this operator: the rest parameter. If we think of the spread operator as someone who takes elements out of a box and spreads them elsewhere, we might say that the rest parameter does the opposite: it collects scattered elements and stores them in a box.

The rest parameter syntax is also an ellipses ... and it allows us to represent an indefinite number of elements as an array. Let’s clarify this with an example:

const author = ['Anne Rice', 1941, 'USA', 'Interview With The Vampire', 'The Vampire Lestat', 'The Queen of the Damned'];const [name, birth, country, ...books] = author;console.log(name);
// Anne Rice
console.log(birth);
// 1941
console.log(country);
// USA
console.log(books);
// ['Interview With The Vampire', 'The Vampire Lestat', 'The Queen of the Damned']

Here, we use destructuring to retrieve the values ​​from the array author and assign them to isolated variables. Following the order of the elements, name, birth and country get the first three values ​​of the array, while books gets the rest (hence rest!) formatted as an array.

And finally, we can also use the rest parameter to represent an indefinite number of arguments in a variadic function — that is, a function that takes an infinite number of parameters.

Let’s use it to create a function that sums up any amount of numbers and returns the result:

function sum (...numbers) {
let result = 0;
for(const number of numbers) {
result += number;
}
return result;
}

We can now call the sum() function with any number of parameters:

sum(1, 2);
// 3
sum(1, 10, 100, 100);
// 1111

That's all for today and see you next time ❤

--

--