What are JS Generators?

shadowtime2000

shadowtime2000

Posted on December 2, 2020

What are JS Generators?

What are JS Generators?

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

Creating

You can create generators like this:

function* myGenerator() {}
Enter fullscreen mode Exit fullscreen mode

The * after function is required.

Yielding

The core mechanic of generators is yielding values.

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

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 = myGenerator.next().value; // 1
const foo = myGenerator.next().value; // "foo"
const bar = myGenerator.next().value; // "bar"
const thingTrue = myGenerator.next().value; // { thing: true }
Enter fullscreen mode Exit fullscreen mode

MDN Docs

You can look more into generators on the MDN docs.

πŸ’– πŸ’ͺ πŸ™… 🚩
shadowtime2000
shadowtime2000

Posted on December 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Message queue with Socket.io
javascript Message queue with Socket.io

May 6, 2024

Hoisting
javascript Hoisting

December 18, 2022

Create a simple Node Server Skeleton.
javascript Create a simple Node Server Skeleton.

December 16, 2022