bhylu.com

Advertisements

JS Generators

A generator function pauses at yield and resumes when the iterator asks for another value. It can express a sequence without building an array first.

Where to run this

This example uses the JavaScript console playground. Select Run to execute it; the example does not run on this lesson page.

A practical example

JavaScript

function* seatNumbers() {
  yield 1;
  yield 2;
  yield 3;
}
console.log([...seatNumbers()]);

What happens

The generator yields [1,2,3].