title: What are JS Generators? published: true date: 2020-12-02 17:55:53 UTC tags: JavaScript,TypeScript,webdev,node canonical_url: https://h.shadowtime2000.com/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() {}

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 };
}

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 }

MDN Docs

You can look more into generators on the MDN docs.

Back | DEV.to

shadowtime2000

If you are looking at this you probably wonder who I am; teenage open source maintainer

shadowtime2000's DEV profile image