Introduction to ES6 generators

Arbaaz

Arbaaz

August 1, 2016

Generators in JavaScript are the functions that can be paused and resumed.

function* genFunc(){...}

Calling genFunc() doesn't execute the body of the function.

const genObj = genFunc();

Instead, it returns generator object which can be used to control the execution of the generator.

genObj.next() will start executing the function and it will execute till it reaches yield keyword.

We can think of yield as return for now. It is similar to C# yield.

function* genFunc() {
  console.log("First");
  yield;
  console.log("Second");
}
const genObj = genFunc();
genObj.next();

/*
output

First
*/

Calling genObj.next() again will resume the further execution after yield.

function* genFunc() {
  console.log("First");
  yield;
  console.log("Second");
}
const genObj = genFunc();
genObj.next();
genObj.next();

/*
output

First
Second
*/

Here's how the execution looks like:

Generator

yield is not allowed inside non-generator functions. That is, yielding in callbacks doesn't work.

We can also pass the data to generator function via next.

function* genFunc() {
  console.log("First");
  const input = yield;
  console.log(input);
  console.log("Second");
}
const genObj = genFunc();
genObj.next();
genObj.next("Third");

/*
output

First
Third
Second
*/

We can retrieve the yielded values via the generator object genObj:

function* genFunc() {
  console.log("First");
  const input = yield;
  console.log(input);
  console.log("Second");
  yield "Forth";
}
const genObj = genFunc();
genObj.next();
const result = genObj.next("Third");
console.log(result);

/*
output

First
Third
Second
{
  done: false,
  value: "Forth"
}
*/

We can have multiple yield in the function as shown in the above example.

Once, the execution of the generator function is completed, further calls to genObj.next() will have no effect.

Further reading

We highly recommend Exploring ES6 by Dr. Axel Rauschmayer to go deeper on this topic.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.