Lingua-e
← Errors
JavaScript

Generator Already Closed: What It Means and How to Fix It

Error reference

Generator Already Closed

Language

JavaScript

Severity

Low

When it happens

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.

Potential fixes

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.

Deep dive

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.

Potential fixes

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.

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 }

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();
}

Practice in English

How would you explain a Generator Already Closed to a fellow dev? Choose the right phrase:

"I hit an error...

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