What is the operator '...' in Javascript?

Asked

Viewed 560 times

12

I saw some uses of ... but I’m not sure what it does. Example:

var a = [1, 2, 3];
var b = [4, 5, ...a];

What’s that operator’s name and how it works?

1 answer

13


It transforms an object that is a data collection into a data list. Its name is spread (documentation).

Can be used to transform a array in arguments for input of a function, in other array, or the creation of an object based on a array.

Not forgetting that a string is still a array.

In his example b will result in 4, 5, 1, 2, 3.

Well roughly speaking, it’s like he copied that list of elements and pasted it to another place that expects a list. This is not how it works because the data collection does not need to have been created as a literal, but understand it so just to better visualize what is occurring.

It would be about the same as:

var a = [1, 2, 3];
var b = [4, 5];
b = b.concat(a);
console.log(b);

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.