Generator Functions

GENERATOR.png

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:

carbon.jpg

You can create a generator function by appending/adding an asterisk after the function keyword.

This will allow us to use the yield expression to generate individual values. You can also yield another generator function by using yield* (yield keyword + asterisk).

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:

carbon+%284%29.jpg

We create a generator named ‘fruitsGenerator’. This function generates the values apple, banana and cantaloupe. The yield keyword is used to pause and resume the function.

carbon (3).png

Then, we create a constant named ‘fruitsIterator’ which contains the iterator object that the generator function returned. This will allow us to control the generator execution.

carbon+%286%29.jpg

With the .next() method, we obtain an object with the value property containing the value yielded. Then, the .next() method resumes the generator function execution with the respective expression.

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.

carbon+%287%29.jpg

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.

Previous
Previous

Prototype Chain

Next
Next

Fetch API