What are JavaScript Generators and how to use them

In this article, we’re going to take a look at the generators that were introduced in ECMAScript 6. We’ll see what it is and then look at some examples of their use.
What are JavaScript Generators?
Generators are functions that you can use to control the iterator. They can be suspended and later resumed at any time.
If that doesn’t make sense, then let’s look at some examples that will explain what generators are, and what’s the difference between a generator and an iterator like for-loop.
This is a for-loop loop that returns a heap of values immediately. What does this code do? — simply repeats numbers from 0 to 5.
Now let’s look at the generator function.
What does it do? In fact, it just wraps our for-loop from the example above with some changes. But the most significant change is that it does not ring immediately. And this is the most important feature in generators — we can get the next value in only when we really need it, not all the values at once. And in some situations it can be very convenient.
The syntax generators
How can we declare the generator function? There is a list of possible ways to do this, but the main thing is to add an asterisk after the function keyword.
As you can see from the example above, we cannot create a generator using the arrow function.
Next-the generator as a method. It is declared in the same way as functions.
Yield
Now let’s take a look at the new keyword yield. It’s a bit like return, but not. Return simply returns the value after the function call, and it will not allow you to do anything else after the return statement.
Yield works different.
Yield returns a value only once, and the next time you call the same function it will move on to the next yield statement.
Also in generators we always get the object as output. It always has two properties value and done. And as you can expect, value - returned value, and done shows us whether the generator has finished its job or not.
Not only can yield be used in generators, return will also return the same object to you, but after you reach the first return statement the generator will finish it’s job.
Yield delegator
Yield with asterisk can delegate it’s work to another generator. This way you can chain as many generators as you want.
Before we move on to methods, let’s take a look at some behavior that may seem rather strange the first time.
This is normal code without any errors, which shows us that yield can return passed value in the call method next().
As you can see in this example yield by default is undefined but if we will pass any value and just calls yield it will return us our passed value. We will use this feature soon.
Methods and initialization
Generators are reusable, but to be so — you need to initialize them, fortunately it is quite simple.
So gen0 and gen1 are won’t affect each other. And gen2 won’t work at all, even more you will get an error. Initialization is important to keep the state of progress.
Now let’s look at the methods that generators give us.
Method next():
This is the main method that you will use most often. It gives us the next output object every time we call it. And when it is done, next() set the done property to true and value to undefined.
Not only next() we can use to iterate generator. But using for-of loop we get all the values (not the object) of our generator.
This will not work with for-in loop and you can’t get access to properties by just typing number — generator[0] = undefined.
Method return():
Return() will ignore any code in the generator function that you have. But will set the value based on a passed argument and set done to be true. Any calls next() after return() will return done-object.
Method throw():
It’s easy one all is throw() do — just throws the error. We can handle it using try — catch.
Implementation of custom methods
We can’t directly access the Generator constructor, so we need to figure out how to add new methods. That’s what I do, but you can choose a different path.
The use of generators!
Previously, we used generators with a known number of iterations. But what if we don’t know how many iterations are needed. To solve this problem, it is enough to create an infinite loop in the function generator. The example below demonstrates this for a function that returns a random number.
It was easy, as for the more complex functions, for example, we can write a function of the throttle. If you don’t know what it is, there’s a great article about it.
But what about something more useful in terms of using generators? If you’ve ever heard of recursions I’m sure you’ve also heard of Fibonacci numbers. Usually it is solved with recursion, but with the help of a generator we can write it this way:
There is no need of recursion more! And we can get the next number, when we really need them.
The use of generators with HTML
Since we are talking about JavaScript the most obvious way to use the generator is to perform some actions with HTML.
So, suppose we have some number of HTML blocks that we want to go through, we can easily achieve this with a generator, but keep in mind that there are many more possible ways to do this without generators.
This is done with a small amount of code.
In fact, only five lines of logic.
That’s it!
There are many more possible ways to use generators. For example, they can be useful when working with asynchronous operations. Or iterate through an on-demand item loop.
I hope this article has helped you better understand JavaScript generators.