Generators - Modern Javascript

Part 2

Generators - Modern Javascript

In our last article, we discussed Iterables and Iterators. If you are still new to these, I suggest reading this first.

This article will discuss Generators and how they are a better alternative to Iterables.


Generators are the special kind of functions that are capable of pausing and resuming the state. They allow us to define an algorithm by writing a function whose execution is not continuous.

Normal functions in Javascript run until they return something or catch any error. If we recall the same function, It will begin from the top again. Unlike normal functions, Generators can

  • Communicate with the caller over the bi-directional channel
  • retain their execution context
function* generate(){

function* is the syntax used to create Generator functions. Its definition will include at least one yield operator which allows pausing the execution of the function until the next value is requested.


function* generate(){
console.log('This will be executed first.');
yield 'Hello';
console.log('This will be executed second.');
yield 'World';

Once called, Generators returns the Generator object which is an Iterator that can be iterated using the next() method. Example:

const generateObject = generate();
--> This will be executed first.
--> Hello
--> This will be executed second.
--> World
--> undefined

This Generator object needs to be assigned to a variable otherwise it will always yield only till the first yield expression on every next(). In order to run again, we need to make different generator object.


  • Lazy Evaluation - It calculates value on demand.
  • Memory Efficient - Because of on-demand calculation, Generators are memory efficient as it doesn't allocate memory unnecessarily. Unlike normal functions, we don't need to pre-generate all values and keep them in memory in case require in the future.


Generators are the functions that return Iterators which can be iterated. The generator object is one-time use only, in order to reuse we need to create a new generator object.

Still, a lot of things are pending to discuss that cannot be covered in this article like Yield, return, and throw operator. We will be discussing this further in the coming articles.

I hope this article will help you to understand the basics of Generators. If you have any suggestions, just let me know in the comments section.