shadowtime2000's Blog

shadowtime2000's Blog

What are JS Generators?

shadowtime2000's photo
·Dec 2, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

What are JS Generators?

Generators are a feature in Javascript which are basically functions that are kind of like iterators.


You can create generators like this:

function* myGenerator() {}

The * after function is required.


The core mechanic of generators is yielding values.

function* myGenerator() {
    yield 1;
    yield "foo";
    yield "bar";
    yield { thing: true };

Taking Values

You have created your generator. Now, we need to use it. When you have a generator, you can call .next() on it, and it will run the generator until it reaches a yield statement. When it reaches it, it will return an object with two parameters, value, and done.

const one =; // 1
const foo =; // "foo"
const bar =; // "bar"
const thingTrue =; // { thing: true }

MDN Docs

You can look more into generators on the MDN docs.

Share this