Learn JavaScript Generators In 12 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
generators in javascript are probably one of the most misunderstood concepts because most people don't really see the use in them but they can actually be incredibly useful in this video i'm going to explain to you what a generator is and show you why they can be incredibly useful welcome back to web dev simplified my name is kyle and my job is to simplify the web for you so you can start building your dream project sooner so if that sounds interesting make sure you subscribe to the channel for more videos just like this to get started i have a very simple generator function on my screen and you're probably already looking at the code a little bit confused because it's really weird compared to normal javascript first weird thing that you're going to notice is we have a star this asterisk symbol after the keyword function the only purpose of this is to tell javascript that this is a generator function we can call the function whatever we want but if we put that star after the function keyword this is what is denoting that this is actually a generator function and then inside the generator function we have three separate yield statements or yielding one then yielding two and then yielding three and yield is essentially like a special type of return keyword that is only useful inside of a generator and that is because the purpose of a generator is to essentially run some code and then return a value and then run some more code and return another value and then run some more code and return another value and so on until you get to the end of all of the code inside of the generator so in order to use a generator we need to run the generator function which is going to return to us a generator object that allows us to manipulate and use this generator let's just get a generator object here and again like i said we just run the generator function and that returns to us a generator object and for now we're going to console.log this generator object so we can see what this looks like as you can see inside of here it's a little bit complicated to see what's going on because we have a bunch of different information showing up inside of here there's really nothing that's making sense but if we dive into the prototypes a little bit you'll see that we have three functions essentially a next function a return function and a row function and really the only function we care about is the next function and next essentially allows us to execute the code inside of our generator so if we just say generator object dot next and we just put this inside of an object so we'll just say value equals that or we'll say obj equals that and let's just console.log this obj now if we save this you'll notice we get an object between return that has a value of 1 and a done of false this is really important anytime that you have a generator it's always going to have a value property and it's going to have a done property done property is either going to be true or false false meaning that there's still more code to run and true meaning that there's nothing and the value is going to be whatever is yielded so when we did generator.next what happens is it ran all the code inside of our generator up to our first yield in our case we just have yield so it's yielding one and then it stops right there if we were to run this next again so let's just modify this code a little bit we'll put the next inside the console log and we'll do that twice so we're going to run next twice notice what happens is we now get two values we get value one and we get value two because it's going from the start of our function to yield one then it pauses until it gets to the next statement we call next then it goes from where it ended to the next yield two and then if we do this another time you notice we get the value of three being printed out if we do it a fourth time you notice our value is undefined and our done is set to true because there's no more code to run in order to see exactly what's going on i want to add some console logs in here i'm just going to say console.log before one then we're going to have an after one and a before two we're gonna have an after two and before three we're also going to have an after three that's going to be all the things that we're going to be logging and for now i just want to do no next at all so when i run my code all i've done is call the generator function and i get a generator object and you'll notice nothing actually gets printed out that's because when you call a generator the very first time all it does is set up the generator object essentially it creates an object that has a next property and the next property allows you to singularly execute through all the code inside the generator if we call next once you're going to notice it prints out before one and then we get the value one that's because it runs all the code from the very beginning all the way to the very first yield now if we run next a second time you'll notice it's printing out after one before two and our value two and that's because the second time we call next it starts right where we finished at that yield and goes all the way to the next yield which allows us to print all of this if we run this again you'll notice we get after two and before three being printed and that's because we go from where we stopped all the way to the next yield and finally if we run this a fourth time you'll see that after three gets printed out it's just going from where we finished all the way down to the very end of our function now one final thing that's important to kind of note about generators is you can actually have multiple generators going at once so let's say i create a generator object and i create a generator object too both based on our simple generator and i execute our generator operator number one twice and then i come in here with our second one and i execute that twice and let's just get rid of all these console logs to make it a little bit simpler you'll notice what happens is it prints out value 1 and value 2 from our first generator object and then it starts back at value 1 for our second generator object and that's because when you call the generator function to create a generator object you're essentially creating a brand new instance an entirely separate object that has its own version of this function that can iterate through things on its own it allows you to do the iterations on their own same thing if i move this down here and i create my generator object 2 here then i keep going through my first one it doesn't actually reset things because this again is a completely brand new instance so whenever you create a generator object it's separate from all the other generator objects that you create that's important to understand now let's kind of talk about what are the use cases for this and one of the most common use cases is when you want to do an infinite loop because in javascript obviously you can't do an infinite loop because you'll just loop forever and freeze up your program but with a generator you can create an infinite loop that actually doesn't stop your computer and freeze your program because you're only executing it one step at a time and this is great if you need to for example generate ids so let's just have a generate id generator and this generator is going to have an id which is going to be equal to 1 when we start we're going to create a while loop that is going to be infinite so we'll just say while true and then inside of here we're just going to yield out our id then we're going to add one to our id so we have essentially a generator that's going to constantly give us a brand new id every single time so let's just come in here we have our generator object and we're just going to call next on it a few times and you can see our value is one two three four and we can call next as many times we want and it's just gonna keep giving us a new number every single time you know three four five six seven eight nine and done is always going to be false that's because the way that this generator works is the first time we call it we're going to have our id set to one we're going to enter the while loop and we're going to yield one then the next time we call it we're going to add one to our id jump back to the start of our while loop and then yield out the new id which is two and we just do that over and over and over and over again forever essentially as long as we want to create ids and if we ever want to reset our ids all we need to do is just create a brand new generator object down here and then when we call that brand new generator object you can see it's starting back over at the value of one so this is a great way to create unique identifiers now the other instance where generators are really useful is a little bit more of an abstract instance and that's the idea of using it as an iterator an iterator is a really common programming concept in a lot of other languages and an iterator is essentially a function or object such as our generator object that has a next property that we can call on it and the next property is going to give us a value and it's going to give us a done flag to let us know if we're done iterating or if we can continue to iterate so for example a very common thing that you might do is just say while object dot next and we just imagine that this object here is some you know like generator object we've created while we have a next one that is not done then we want to do some code that's inside here so while next dot done is not equal to false you know for example this then we do some code down here this is a really common use case for iterators and this is something that you'll see a lot inside of code especially when you're writing libraries iterators come in super handy and if you're coming from other programming languages like java for example you'll be really familiar with iterators because they're a very common use case in those different languages so that's really the idea behind generators is they allow you to really easily create iterators without having to do all the hard work behind the scenes for example you can actually create a generator for an array really easily for example we can just say generator here that takes in an array and all we want to do is just convert this to an iterator so we can just say before let i equals zero i is less than array dot length i plus plus all we want to do is yield our array of index i that is around us to create an iterator for our array super easy now we can just say generator we'll pass an array of one three and five and let's just come in here we'll just say generator object.next you can see we get the value of one we get the value of three we get the value of five and one more time you can see we get the value of undefined and done as true so this is a really easy way to convert an array into an iterator style syntax if you want to use it because there's a lot of libraries in javascript which rely on using iterators instead of arrays or they give you iterators instead of arrays understanding how iterators and arrays work along with generators is really important now if we just go back here a little ways to our while loop that we had before for generating unique ids i'm going to explain a few unique things about generators that you should probably understand and those unique things are essentially going to be how we can handle next more uniquely and also additional things that we can do besides next so let's modify our code really slightly here so we can actually take a value in from yield so i just want to say const increment is going to be equal to yielding of our id and if increment is not equal to null so if we pass an increment value if it's not equal to null then what i want to do inside of here is i just want to take our id and i want to add our increment to it otherwise i just want to increment our id by 1 by default so this essentially allows us to pass a value back through our yield to do the incrementing with so if we just kind of clean this up a little bit and notice here our value is one two you know three four it's incrementing by one but if we pass a value to next let's say we pass it four you're gonna notice now our first value is 1 then our next value is 5 and it's adding by 4. that's because whatever you pass to next actually gets returned from yield and then it's going to be used for the next iteration so we return 4 from yield which is our increment and we're adding that 4 to our id and then yielding that id so that's what passing the value to next allows you to do this isn't something you're going to do all that often but it's pretty powerful because you can do a lot of cool things by passing the value into next for example we can pass in 3 here now we have 1 we have 5 we have eight and then since we didn't pass anything to next here we're just getting nine the only important thing to note is that passing a value to next on the first iteration does absolutely nothing because there is no yield to return to we're actually just coming from our generate id up here so if you're going to pass a value to next you can only do it on the second iteration of next and every single one after that now another important thing to know about the generator object is it has a function called return and return is really interesting because return allows you to essentially exit out of a generator no matter how much more you have to go it'll just return whatever value you pass it so let's just say we pass it the value of 10 and we'll keep everything else the same now we save you can see it goes 1 2 10 and that's because we're passing 10 to return and now our done is set to true and undefined as being returned as our value that's because when we call return it's exiting out of our generator function as if it finished and it's just going to return this value right here so it immediately exits our generator and does not allow us to have any more information in our generator at all this is really great if you need to exit out of the generator prematurely you can just use return and it's going to exit out immediately now the very last function to worry about is going to be the throw function and this is just going to allow you to throw an error if you have an error we can just say you know new error i now if we save you can see it's throwing that error high and it's throwing it for our generator this isn't really something super useful unless you're kind of like writing a library behind the scenes but it's important to know that it's there and that's everything there is to the generator function if you enjoyed this video i highly recommend you check out my full javascript simplified course which dives into topics such as this and other complex topics most people don't even know exist so you can really take your javascript skills to the next level so i highly recommend you check out this course linked down in the description below with that said thank you very much for watching this video and have a good day
Info
Channel: Web Dev Simplified
Views: 73,183
Rating: 4.9646692 out of 5
Keywords: webdevsimplified, javascript generator, js generator, generator function, javascript generator function, javascript generator tutorial, js generator tutorial, js generator next, js iterator, javascript iterator, javascript, js, iterator
Id: IJ6EgdiI_wU
Channel Id: undefined
Length: 12min 11sec (731 seconds)
Published: Sat Jul 31 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.