How to use Generator Functions in JavaScript - Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys he going in this video I'm gonna be showing you the basics of generator functions in JavaScript and how you can use them to improve your JavaScript code so what are generator functions were basically they're a special kind of function which allow you to suspend their execution so basically you're able to execute these functions and then you can actually press pause on their execution you can do something else and then come back and continue where you left off so they sound a bit complex when you put it like that but they're actually really easy and straightforward to use they also simplify the creation of innovators which I'll get into a bit later on but for now I'm gonna stop talking here and demonstrate how they work with some JavaScript code so let's go inside the text editor right here and firstly we're gonna define or create a generator function so we can say here function and then we can put an asterisk right there we can then specify the function name in this case I'm gonna call this function generator example just like this okay so now we have created a generator function okay and that is done using the asterisk right after the function keyword so now I'm going to type out here yields and say 8 so basically this yield keyword is the way in which you actually extract or receive the values from a generator function regular functions use the return keyword just like this okay but generator functions use the yield keyword to provide you with a value so that means when I see this function right here this is telling me that this function is gonna give me a single value of 8 okay if I was to make this 9 and tenon essentially are call yield three times this now tells me that I'm going to get a total of three values from this function eight nine and so now with these multiple yields this means that if I was to use this generator function when I first step into and start executing the function it is going to give me a value of 8 it is then going to be suspended when you use the yield keyword you are not only getting a value but you are also suspending the execution of the function okay so once you have suspended the execution of the function right here if I was to go back in and I start executing the function once again it is going to essentially start executing from this line right here it's going to give me a value of 9 it is then going to be suspended once again and then I can go back in and I can essentially start executing it once again and this time is going to continue and start executing from this line onwards so that's basically how they work and I'm gonna demonstrate this right here and make it really easy to understand but firstly we are going to actually retrieve a generator from this function okay so essentially I'm gonna say constant a is equal to generator example just like this so I'm gonna be calling the generator function just like this okay and of course I'm actually not doing our return so you might be asking since there is no return in the function what value does this generate a constant half well basically when you call generator functions like this what you're gonna get is a generator object okay so at this point in time by calling this function none of this code is actually executed just yet so false to say for example console dot log and logout something like decode okay I'm gonna save this and refresh the browser here and we can see we actually get nothing in the console because as of yet we are we haven't actually started executing the code inside this body all we're doing is creating a generator object for this function so let's now console dot log the generator objects okay I'm gonna save this and refresh and you can see in the console we get here a generator object prototype generator okay so this thing has quite a few things going on we can see new generator status as being suspended but more importantly if I was to expand this right here we can see we have a method called next so this right here this next method is vital to the usage of generator functions basically this next method is going to allow you to retrieve the values that you provide with yield okay so basically I can call this next method on this generator object three times and I'm gonna get eight nine and ten as my values so let's demonstrate this I'm gonna say console.log generator dot next I'm gonna do this four times one more time than the amount of yields inside this function I'm gonna save this here and refresh the browser and we get here four objects the first time that we called the next method we get value as being eight and we get done as being false we get these two properties inside this object as the return value from the next method of course here the value as being eight is what I put inside the first yield okay it is then telling me that I still am not finished with the generator function okay so this happens of course one two and three times one for each yield and then we get value and defined and done true so of course once we do this three times there is no more left to execute there are no more yields so we of course get undefined as the value and done as being true we are now finished with the generator function so what's happened here is essentially we have with the with the first call of the next method we've retrieved the value of eight the function is then suspended at this line we can then go here and do other things okay do what we want okay and then we can come back and call next once again this time it's gonna remember where it left off earlier and it's gonna give me the value of then nine then once again it's going to be suspended and the same thing happens for ten and then of course the undefined value right here and right there that is basically how generator functions work okay cool so now I also want to show you what happens when you put a return statement inside here what if I was to say return and then say 11 okay if I wants to do this I'm gonna save this and refresh we can see here we get 8 9 10 11 and then done as being true so you actually get the last value here with the return but the return automatically sets done as being true ok so that's what the return does it works very similar to the yield okay so then I sorry so then if I was to say you can't say 12 I then call it a fifth time save this and refresh we get undefined and done true because of course we did the return here if I was to make this once again yield 11 save this and refresh of course we then get 12 and then once again done false so that's what that's what the return statement does in a in a generator function okay so I also just want to log out the generator object once again so I'm going to say consult our log generator just like this I'm gonna say this and refresh once again and expand this we consider this actual this objects implements both the iterator and the iterable protocol which means if I wants to expand this prototype here we can see we get firstly a symbol to iterator right here so that implements the iterable protocol we also of course gets the next method which of course means it implements the iterator protocol so with this being said it can definitely simplify the creation of iterators because we can essentially use this like an iterator okay so this means that if I was to go back inside here I can do a four of loop over this generator function I can say for const end of a generator example just like this I can say consult log in and now we're gonna get these numbers in the console I'm gonna save this and refresh and we can see we get 8 9 10 11 and then of course 12 so that right there is the basic usage of generator functions but they become really powerful when you start using variables because of course when you define a variable inside here right this variable if you modify it's gonna maintain its value as you continue executing the function so let's demonstrate the usage of variables in generator functions so I'm gonna get rid of all this stuff and show you a second example so this example is going to essentially create a generator function which will give me squared numbers essentially I want this I want 1 so 1 4 9 16 25 36 and so on from this generator function which I'm about to define so we can say function right here of course make it a generator function I'm going to call this a create squared is generator just like this so now inside here we are going to define a number to actually keep track of so we're gonna say let's M as being zero so now this variable lets us keep track of which number we are up to for these squared numbers okay so then we can say Wow and then true okay we can say n plus plus and then yield and times n so basically we're introducing a bit more complex logic in this function but essentially we can continue calling next on this generator continuingly okay I'm gonna keep getting this the actual squared numbers okay so let's actually go down here and do a Const of squared numbers equal to a create squared numbers generator I'm then gonna say console.log squared numbers got next and I'm gonna say simply value to get that direct value from the return object I don't do this three times okay so now I'm gonna save this and refresh and we get 1 4 and 9 so what's happened here is of course the same thing is previously on the first call of the next method we start here it firstly defines n is being 0 it then does an infinite loop ok and it's of course going to increment n by 1 and then of course return you your n times n so for the first run it's going to be 1 times 1 and then it's gonna pause or suspend right here we're gonna call it a second time it's going to go back up to the top here and of course do the same thing and then so on so essentially we've created an infinite way for us to get squared numbers ok so you can see here you can start to see the benefits of using a generator function because but here this variable is maintaining its value as we continue to call the next method okay cool so let's take it one step further by actually passing in a a maximum number to this function so we can say for example max and right here then we can say while M is less than max so now we can directly use this in a for loop so I can say for example for constant end of creates weird numbers generator and passing 10 for example I can console dot log n right here so now I'm gonna save this and refresh of course we get 1 4 9 16 and onwards up until 10 times 10 which gives us of course 100 okay so of course if I wasn't to use the parameter here this would go on forever and of course creates an infinite loop okay so that what they're using variables and maintaining the variable value is definitely one of the main reasons to use generator functions and of course it actually makes them really powerful so let's take a look at one more example and this one is going to be a lot more useful okay so essentially I'm going to create a generator function which is going to allow me to retrieve random unique values from an array so basically they also define an array right here of names for example Dom Shelly Timmy and Marie I then want to pick names at random from this array but not the same name twice we can do this using generator functions so the usage might look like this you can make a constant court unique names this will be the actual generator itself equal to a creates a unique so create unique random generator just like this and pass in the actual name so of course we're going to be defining this generator function in a little bit but then we can of course say for constant name of unique names you can say console.log name so essentially this one he is the usage of this generator function to of course pick random names from this array but not the same name twice so let's go up here and make a new function a generator function call this function creates unique random generator it's going to accept of course an array just like that and now we're going to firstly define a constant cord available equal to the array we passed in so basically this isn't to required but the available constant makes it a bit clearer and easier to read what's actually going on so then we're gonna say while available that length does not equal to zero okay just like this we are going to do something so basically this available array contains all of our available values as we use the values that random we're going to be removing the values from this array that's why we're saying while there are still values that are available we're going to be returning them to the user of the generator function so we can say Const random index is equal to math.floor math.random times available length and basically this flooding is going to give us a random number a random index for the available array okay we can then say Const value is equal to available and then acts at the event in an index so this one here is going to contain one of the names picked at random okay we can then move have been used values from the list of available values so we're gonna say available dot splice at random index one so basically this here is going to remove this name from the list of available names okay and this basically allows the while loop to then eventually finish we can then say yield and say name we're going to be yielding and giving the user the name which we picked at random okay so now I'm gonna save this here and refresh once again we get four things let's just go back and actually see what actually happened here to be honest I'm actually not not too sure what happened I'm sorry of course yield value I'm gonna save this now refresh once again and we get here ret me done and Shelley refresh one more time we get a different order of names and of course the names are always going to be unique and that what there is generator functions in JavaScript thanks for watching guys and I'll see you later
Info
Channel: dcode
Views: 19,696
Rating: 4.952024 out of 5
Keywords: code, coding, programming, tutorial, introduction, beginner, walkthrough, guide, software, development, simple, easy, into, english, with, example, examples, developer, lecture, recording, how, to, js, javascript, es6, ecmascript2015, new, features, html, css, web, website, node, nodejs, promise, return, yield, asynchronous, async, co js, co, function, object, await, iterator, iterable, asterisk, computed, generator, for, of, loop, while
Id: EzdgkEMvrvA
Channel Id: undefined
Length: 18min 47sec (1127 seconds)
Published: Mon Aug 26 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.