JavaScript Generators
JavaScript has many amazing ways to work with data. We have previously looked at loops that will iterate over an array of data and work with each piece individually. This week, we look at two types of functions that do this with a bit more power than before as they can both hold off on performing more loops through the code until you want to restart it again. These functions are called iterators and generators. The only difference between these functions is how they are set up. Generators need to have an asterisk placed at the end of the “function” keyword or at the beginning of the function’s name (Corso, 2019). Also, iterators need a way to hold the state of the loop. It needs to hold the information of if you have looped through all possible options and have come to the end. Generators have this backed in as generators return an object of values and a Boolean state of being at the end or not (n.d.).
With the use of promises, these functions aren’t used that much, but I did find some unique ways to utilize generators. On sites like TikTok, YouTube, and Facebook, the entire site could not be loaded all at once. You get more content as you scroll down the page. Generators could be used to pause loading the entire page and only load chunk by chuck as you scroll. Another option is in a form on a site. You could load each section of the form at once with the country and address lines there connected to an API, or you could pause the loading of an address API by narrowing it down by country, then load the subsections, then load the address API and verify the data by matching it to one in the database.
Get Ace D Baugh’s stories in your inbox
Join Medium for free to get updates from this writer.
Generators don’t seem to be used much, but they have their benefits in programming and I can see why someone would choose them due to their ability to pause a loop and resume when needed.
References
Corso, Domenic. (2019). How to use Generator Functions in JavaScript — Tutorial. YouTube. Retrieved September 6, 2022, from https://www.youtube.com/watch?v=EzdgkEMvrvA.
Function* — javascript: MDN. JavaScript | MDN. (n.d.). Retrieved September 6, 2022, from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*




