DEV Community

Arhan Khan
Arhan Khan

Posted on

Generators in JavaScript: Functions That Can Pause

A normal function runs from start to finish in one go. A generator function can pause in the middle, hand a value back, and resume later exactly where it stopped. That makes it perfect for producing values one at a time — without building a giant array first.

You write a generator with function* and pause it with yield:

function* countUp() {
  yield 1;
  yield 2;
  yield 3;
}

const counter = countUp();
console.log(counter.next()); // { value: 1, done: false }
console.log(counter.next()); // { value: 2, done: false }
console.log(counter.next()); // { value: 3, done: false }
console.log(counter.next()); // { value: undefined, done: true }
Enter fullscreen mode Exit fullscreen mode

Each call to next() runs the function until the next yield, then pauses again. The returned object tells you the value and whether the generator is finished.

Generators are most useful when the sequence is long or infinite. An ID generator, for example, can produce IDs forever without storing them all:

function* idGenerator() {
  let id = 1;
  while (true) {
    yield id++;
  }
}
const ids = idGenerator();
console.log(ids.next().value); // 1
console.log(ids.next().value); // 2
Enter fullscreen mode Exit fullscreen mode

They also work with for...of, which calls next() for you until done is true. And because a generator only computes the next value when asked, it uses almost no memory — ideal for paginating data or streaming results.

You will not reach for generators every day. But when you need lazy, one-at-a-time values — infinite sequences, step-by-step processes, custom iteration — nothing else does the job as cleanly.

Top comments (0)