Lingua-e
JavaScript

What is a Generator Already Closed?

← Errors

Once a generator function returns (or its body is exhausted), calling .next() on it returns { value: undefined, done: true } silently rather than throwing an error. This can cause subtle bugs where a loop or consumer silently stops receiving values without any indication of why.

Why it happens

  • Calling .next() after the generator has already returned or thrown.
  • An early return statement exits the generator before all values are yielded.
  • Calling gen.return() explicitly closes the generator.
  • An exception thrown inside the generator closes it.

Examples

JavaScript

Code that triggers the error

function* counter() {
  yield 1;
  yield 2;
}

const gen = counter();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: undefined, done: true }
console.log(gen.next()); // { value: undefined, done: true } -- silently no-ops

Error output

{ value: 1, done: false }
{ value: 2, done: false }
{ value: undefined, done: true }
{ value: undefined, done: true }

How to fix it

Always check the done property from .next() results. Use for...of loops which handle the done signal automatically. If you need a restartable source of values, recreate the generator rather than reusing a closed one.

Fixed code

function* counter() {
  yield 1;
  yield 2;
}

const gen = counter();
let result = gen.next();
while (!result.done) {
  console.log(result.value);
  result = gen.next();
}

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free