Back to Blog Listing

A Guide to JavaScript Generators and Iterators

Generators are special functions that can be paused mid-execution, allowing other code to run in the meantime, and then resumed from where they were paused. They are powerful for writing custom iterators and handling asynchronous streams.

Generator Syntax

A generator function is declared with an asterisk (function*) and uses the yield keyword to return values sequentially.

function* numberGenerator() {
  yield 1;
  yield 2;
  yield 3;
}
const gen = numberGenerator(); // Returns a generator object
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }

Infinite Streams

Because generators evaluate expressions lazily, they can generate infinite sequences without running out of memory:

function* infiniteIds() {
  let id = 1;
  while (true) {
    yield id++;
  }
}
const ids = infiniteIds();
console.log(ids.next().value); // 1
console.log(ids.next().value); // 2
💻

Try this code in our online compiler!

Don't just read about it. Write, run, and experiment with these JavaScript concepts instantly on our online workspace with autocomplete suggestions.

Share this tutorial:

CodeCompile