Using the ES6 spread operator

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 8 years ago
Updated 3 years ago

The spread operator allows you to "explode" an array into its individual elements.

Man 1: [00:00] The spread operator allows you to take an array and spread it out into its individual items. If I log out an array with one, two, three you can see I get an array, so you have the brackets with one, two, and three.

[00:12] If I put the three dots in front to say I want to spread this array and I hit run again, you can see I get one and two and three with no brackets around it. This actually allows us to push elements easily into other arrays. Before if I were to do first push second and log this out, you'll see, I'll get one two three and then another array inside of my array.

[00:40] But instead, if I spread out the second array and push that in, you can see I get the individual items pushed in. I could actually duplicate that and save and you can see I get one two three, four five six, four five six. So I'm pushing in the individual items over and over instead of pushing in arrays.

[01:02] This even works for doing things like pushing in an array of parameters. If I want to add three things and then push in my first collection there, hit run, you can see I get six, which is one plus two plus three. I just passed in first and then I spread it out into one, two, and three and I can do the same thing for second and run this and you'll see I'll get 6 and 15. 15 being 4 plus 5 plus 6, which is 4 plus 5 plus 6. Because, again, this, these three dots, are spreading the array out into its individual elements.