What is the role of the spread operator in this javascript code?

616 Views Asked by At

Today I read this article in medium, and I don't understand about spread operator below.

enter image description here

I know that the spread operator is used to receive array as a parameter in a function. In the code above, what does the spread operator do? Convert object to array?

3

There are 3 best solutions below

1
On BEST ANSWER

I know that the spread operator is used to receive array as a parameter in a function

In that context, three dots ... are referred to as rest parameters syntax, not spread syntax. In the code included in your question, the context in which three dots ... are used, it is known as spread syntax.

In the code above, what does the spread operator do?

It iterates over the Set and spreads (adds) the entries in the Set in to a new array

Following code snippet shows a simple example:

const set = new Set([1,2,3]);
const newArr = [...set];

console.log(newArr);

0
On

The spread operator, in combination with the array syntax ([]) takes the values from the Set and, for lack of better term, spreads them out, so you get an array with all the values in the Set. The end result is that you transform an array to another array that holds the unique values from the original array.

1
On

Lets look at it line by line.

var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]

This creates an array entries with some list of numbers.

Now when we do, new Set(entries), we create a Set from entries array. A Set is a collection of distinct elements as you may already know.

Hence, new Set(entries) gives us a Set from entries as follows: Set(8) {1, 2, 3, 4, 5, …}

Now, ... operator spreads the distinct elements from the Set to create an array, which is the line - var unique_entries = [...new Set(entries)]