Generator Functions in JavaScript

Hey Guys ! Hope you are all good. Today we are going to talk about a new feature introduced in javascript Es6, the Generator Functions. There have been a lot of buzz about these functions and according to some people and including myself they are a real game changer.

What are Generator Functions ?

To answer the question as simple as possible these “generator functions” are special functions that have the ability to pause your code. wait what ? Yes they can hold the execution at particular interval. They are also called iterable functions. But lets ignore that for now and i will get back on why they are called iterable functions.

Here is how you define a generator function

Its defined regularly as any other function. It can have parameters like any other function. The only difference that makes it a generator function is the “*” right after the function keyword.

Something about ‘Pausing’ the executing of the code …

A special keyword has been introduced in javascript called “Yield”. It can only be used inside a generator function and is used to pause the execution of the code. Let jump into the code now.

I have created a simple function that takes two numbers in parameters and adds them together and return the result. Notice how i have used yield three times. Every time yield appears it stops the execution of that function until we resumes it. Now lets run a generator function.

First we initialize the generator function then we executed it by calling the next method of that initialized generator. Each time we run “Next” it returns us an object that shows the status of the generator function and the value being yielded. When the first next was called function ran until it hits the first yield keyword where it stopped and yielded the value of  “num variable” which is 2 in this case. second time it stop it yielded the value of 5 and showed status that it is not completed and can go on more. The third time we ran next it returned NAN. Why would it return not a number ?. We are adding the two number variables which we assigned earlier with our “num” variables. Well the trick is that yield is sitting between the value you are assigning and the variable. So to make this function work we have to pass in the values we received in the next function as a parameter.

Now in this case, we created a variable called “yieldedObject”  and assigned it the object that was returned from our first next call. In our second call to next we passed in the value, that we received in this case it was “2”. At the third call to next we passed in the value that we received in the previous call to next which is “5”.

The object returned from the third call to next was the sum 7 with the done status false.

Third yield was the last yield in the function but still it wasn’t completed so we ran the next one more time (The forth Time). We received the following.

The “value” property is the value that is returned in the function since we were returning the sum we got 7 . and the “done”  property indicates that the function has ran completely. If we run the next function again we will get following result.

Indicating the function has ran completely and there is nothing to return or yield.

To yield or Not to yield

It’s not necessary to pass the yielded value in the next function we can pass anything we like. In this case on the third call to next, i passed in “1”,  hence the result of our sum is now “3”.

Iterating Over Generators

As mentioned earlier generator functions are called “iterable functions” because we can iterate over these functions. Here i created a simple generator that creates infinite even series.

We are going to use the new and shiny “for of loop” of ES6 to iterate over the results of our evenNumberSeries generator. It will break the loop if the number value is greater then 200.

That’s why generators are sometimes called iterable functions.

Use Cases for Generators

You must be wondering that’s interesting and all, but where can it be used ? Well for starters we can use it with promises.

Here is are generator function. Let’s suppose we make an API call or do some I/O operation that returns a promise. Yield will wait until the Promise is resolves or rejected. That way our code can be “Synchronously Asynchronous”. Note that is the promise is rejected it will throw an exception so we must use a try-catch block to catch it.

To run the generator completely like a normal function without calling next function . There are many libraries that wraps the generator functions like co and bluebird I mostly use co.

Conclusion:

Generators are great new feature that can be used in many ways. People are still experimenting with this new feature. Hope this blog was helpful. Let me know if there are any queries. You can leave a comment or drop a message in my inbox. Until then Have a good day or night 🙂

1 thought on “Generator Functions in JavaScript

Leave a Reply to Alief Kusumaningtyas Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.