Generators in JavaScript

Image for post
Image for post
Photo by Louis-Etienne Foy on Unsplash

In the last blog, we were talking about Iterators and the pros and cons of it. So in this blog, we will be looking at Generators and how it is “better” than Iterators.

The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.

It’s better than iterators in that Generator functions provide a powerful way to define an iterative algorithm by writing a single function whose execution is not continuous.

Generator functions are written using the function* syntax.

When called, generator functions return a special type of iterator, called a Generator. Whennext method gets called on the Generator, the Generator function executes until it encounters the yield keyword.

The function can be called as many times as desired, and returns a new Generator each time. However each Generator may only be iterated once.

See below an infinite loop Generator:

To get the value using for...of loop:

Accessing it using spread syntax:

Since Generator returns an iterator (noting the calling of next() ). The result of next() is always an object with two properties:

  • value: the yielded value.
  • done: true if the function code has finished, otherwise false.

How do we reach the last item in the iterator?

Well, each time a yield is encountered it measn the done is set to false . So to get the last item with done set to true , we use return keyword (Any yield after this return is ignored).

Also note that a generator object is both an iterator and an iterable.

The yield is a magical keyword that can do more things other than simply return a value and next() can do more things aside from retrieving the value.

  • passing argument to next()

The argument passed to next() will be received by yield :

  • passing a function to yield

Apart from returning values yield can also call function.

  • delegating to another generator or iterable using yield* expression
  • async generators

To asynchronously generates a list of values (e.g. continuous calls to api), we can create an asynchronous generator.

You can also chain the Promise:

In general, Generators are a special kind of Iterators using yield keyword and implementing iteration protocols. It is really useful in Lazy Evaluation as the value can be retrieved on demand and thus memory efficient.

There’s more to cover on Generator. I found resources on MDN very useful to get the basic right, so is reading python related concepts such as .

That is so much of it!

Happy Reading!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store