Check out a free preview of the full Professional JS: Features You Need to Know course

The "Rest & Spread" Lesson is part of the full, Professional JS: Features You Need to Know course featured in this preview video. Here's what you'd learn in this lesson:

Maximiliano demonstrates using the rest and spread operators in JavaScript. The rest operator is used to collect multiple arguments into an array, while the spread operator is used to spread the contents of an array into another array.

Preview
Close
Get $100 Off
Get $100 Off!

Transcript from the "Rest & Spread" Lesson

[00:00:00]
>> Maximiliano Firtman: Rest and spread operator, it's the same operator but used in different places. It's when you use three dots. Three dots, that's new in EF6. So the rest operator is when you use it in arguments, for example. So for example, if I'm saying collect, I can call collect and I'm passing values, okay?

[00:00:25]
Here any kind of arguments, any amount of arguments, so collect will actually rest will take them, all of them and we'll put them into an array, okay? So Args is an array, but also I can say A, V and R. Here you will understand why it's called the rest.

[00:00:50]
So here I'm saying I wanna collect two arguments, A and B, and the rest of the arguments, I wanna collect them in an array. So now Arg sub 0 will be 4 because 2 will go to A, 3 will go to B, and the rest will be collected under Args array.

[00:01:15]
>> Maximiliano Firtman: Okay, make sense? It's just that. So you can collect all the arguments or only the after 1, 2, or 3 or 4 name arguments that you want and how in mind this works also in arrow functions. I mentioned before that there is an arguments array always available in functions, but not in arrow functions.

[00:01:37]
But if you use the rest operator it works on every function, arrow or not arrow, okay? And the same operator with a different name, it's called the spread operator when you use it in arrays. So now let me remove this for a while, for a second, so we can see this.

[00:01:55]
So I'm creating an array here, 1, 2, 3, and then I'm creating a new array that says it will contain 4, 5, and here is spread me everything from this other array. So that's why we have 4 and 5 and the rest is 1, 2, 3. This is the final array.

[00:02:15]
So you are spreading the contents of one array into another array. Also, this is a quick way to create a copy. Not the best way but a quick way to create a copy, you open a new array and you spread the other one.
>> Maximiliano Firtman: This is creating a new array spreading the contents of the previous one

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now