Generator Functions
Hey there!
In this entry we’ll talk about Generator functions. We’ll take a look at some examples and basic syntax along the way.
Generators are a special type of function. You use them when you want to obtain multiple values on a ‘per request basis’, meaning pausing the function’s execution between the requests but resuming where you left on (like a bookmark). That’s the beauty of generators.
You might be asking what advantages do generators provide? Well, (to name a few) they can help simplify convoluted loops, implement iterables, infinite data streams, etc.
Let’s talk about the basic syntax of a Generator function:
Keep in mind that you need to explicitly ask the generator for a new value. You will receive a value if there is any or you’ll be notified if it has no more values to produce.
Important: Calling a generator does not execute the function’s body right away, it returns an iterator (object) that allows us to communicate and obtain values from the generator.
Let’s look at this example that is using a generator function to generate a sequence of fruits. We’ll break down this code to better understand what’s happening:
The generator executes its code until it encounters the yield keyword that produces one item of the sequence, then returns a new object that has the respective result. After that the generator stops its execution until it gets another request.
We can also use a for-of loop to iterate through the entire generator function.
To conclude, generators in JavaScript are useful since they are functions that can be paused and later re-executed at any given moment without their context changing.