Basics of Generator functions in JavaScript

Moatez Bejaoui
eDonec
Published in
3 min readMar 3, 2021

In this article, I will be showing you the basics of generator functions in JavaScript and how you can use them to improve your code.

What is a generator function?

Introduction

Generator function.

A generator is a function that can stop midway and then continue from where it stopped. In short, a generator appears to be a function, but it behaves like an iterator.

So let's code!

We will be creating a generator function in this example.

function* generatorFunction() {
yield 1;
yield 2;
yield 3;
}

Basically, yield is the return of a generator function in our case this function will be giving us 3 values of 1 & 2 & 3, next we need to retrieve a generator from this function like the following.

const generator = generatorFunction();

if we log our generator it will be giving us a generator object

as you can see there is a next method that going to allow you to retrieve the values that you provided with yield but in an object that has {value: “the value”, done: “if the function is done or not”.}

so here we will be logging this next() 4 times and let's see what happens.

const generator = generatorFunction();console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());

as we can see the yield ends at 3 so the 4'th log will have an undefined value and done will be true.

Since our generator object implements the iterator and the iterable protocol

so I will be logging our generator object once again

if you need to know more about iterable protocol click here

A generator function simplifies the use of an iterator like the following

for (const n of generatorFunction()) {
console.log(n);
}

And the result will be 1 & 2 & 3.

Q&A

If something doesn’t work as expected or needs more details, just drop a comment below :) Happy coding!

This has been developed by myself at eDonec.

--

--