Rest and Spread Operators - Let's Learn ECMAScript 2021 with Earl Duque
Okay. So for
this video, we're going to be talking about the rest operator
alongside the spread operator. Both of them look like this dot, dot, dot. All right. Okay. So the rest operator allows us to represent an indefinite number
of arguments as an array, and then the spread operator
is taking something like an array and spreading them out into individual
elements. It's probably easier if I show you. So, you know, let me jump right in. So say we have a function
called logIncidents. inside of it we are expecting an array, so an array called incidentIDs. And in that we are going to call in for each statement for this, and then we're going to go ahead
and use our new arrow functions. So for each ID in there, we're going
to go ahead and log a statement saying logging. And then the id. and then let's call that function. Call logIncidents. And we're going to give it an array of an inc001 and inc002 and inc003. If I go ahead and run that, we'll see that it properly logged
each one. We're going to be calling this function
throughout my script. And we don't know how many parameters
that we might actually be giving it. But instead of an array
being provided into this, what if we needed to provide
a bunch of parameters that strings? In fact, I'm going to go ahead
and add a fourth one here. So now we have four string parameters
getting input into this function. How do we denote that
and still make this operate as a for each for all of those parameters, we simply add
the rest operator in front of there. And so this three dots basically say, hey,
take all the things that are being provided inside of this parameter
and then turn it into an array. And if I press run script,
the same thing happens, same thing there. So it's another way to denote it. The spread operator on the other hand,
is all about displaying everything
that's available within that array. So let's say I have one array that is that inc001
and it has inc002 in it. And then I have another array that has inc003 in it and inc004 in it if I want to combine them,
I can just simply do this. Now. Combined equals the first array and the second array. So what that looks like is that it's taking that first array
and it's spreading it out. It's taking all of its elements and then listing them all out
as individual elements. So it's as if I was copying
and pasting this string in here, and then this string in here,
and then this string in here and so on. It's spreading it out. And so if I run the script,
you'll see that this is... I mean, it's
showing this array as a string, but you'll see now it combined
both of those arrays into one So those three dots are adding some
functionality to how you play with arrays.
https://www.youtube.com/watch?v=VfI0zTTkHvA