# Generator Functions

> What are generator functions (function) in JavaScript, how does yield pause and resume execution, and what are their practical use cases?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-generators
Last updated: 2026-11-28

Difficulty: Advanced

## Question

What are generator functions (function\*) in JavaScript, how does yield pause and resume execution, and what are their practical use cases?

## Answer

A generator function, declared with `function*`, returns a generator object instead of running its body immediately. Each call to the generator's `next()` runs the body until the next `yield`, hands out that value as `{ value, done: false }`, and freezes the function's local state until `next()` is called again. This makes generators the simplest way to write lazy sequences, custom iterators and pausable workflows.

### How pausing and resuming works

1. Calling `gen()` does not execute any code. It creates a generator object in the "suspended start" state.
2. `it.next()` runs until the first `yield expr` and returns `{ value: expr, done: false }`.
3. The next `it.next(x)` resumes right after that `yield`, and the `yield` expression itself evaluates to `x`. This is two-way communication.
4. When the function hits `return v` or the end, `next()` returns `{ value: v, done: true }` (value is `undefined` without a return).
5. `it.return(v)` ends the generator early (running any `finally` blocks), and `it.throw(err)` throws an error at the paused `yield`.

Note that the argument to the very first `next()` is ignored, because there is no paused `yield` to receive it yet.

### Generators and the iterator protocol

A generator object is both an iterator (it has `next()`) and an iterable (its `[Symbol.iterator]()` returns itself). So it works anywhere an iterable is accepted: `for...of`, spread `[...gen()]`, destructuring, `Array.from`, `new Set(gen())`. Writing `*[Symbol.iterator]() { ... }` inside a class is the cleanest way to make your own data structure iterable.

One subtlety: `for...of` ignores the final `return` value, because it stops as soon as `done` is `true`.

### Practical use cases

- **Lazy and infinite sequences**: IDs, Fibonacci numbers, pagination cursors. Values are computed only when asked for, so `take(5, naturals())` is cheap.
- **Custom iterables**: trees, linked lists and graphs can expose traversal order with `yield*` recursion.
- **Pipelines**: chain `map`, `filter`, `take` over generators to process large data without building intermediate arrays.
- **State machines and coroutines**: a step-by-step wizard or a game loop that resumes where it left off.
- **Historical async control flow**: libraries like `co` and Redux-Saga use generators to write async code that looks synchronous. `async/await` largely replaced the `co` pattern, but Redux-Saga still uses generators because effects can be tested by stepping through `next()`.

### Gotchas

- A generator object can be iterated only once. After it is done, `for...of` produces nothing.
- Arrow functions cannot be generators; there is no `*` arrow syntax.
- `yield` is only valid directly inside the generator body, not inside a nested callback such as `forEach`.
- Breaking out of `for...of` calls `return()` on the generator, so `finally` blocks run. That is useful for cleanup.
- For asynchronous streams, use async generators (`async function*` with `for await...of`), which are a separate feature.

**Pausing and resuming a generator. Change the values passed into next(), or exit early with return(), under Tweak.**

1. **Calling a generator runs nothing**: It returns an iterator paused before the first line.
2. **next() runs to the next yield**: yield sends a value out and freezes the function.
3. **next(value) resumes it**: The paused yield expression evaluates to the value passed in.
4. **return ends it**: The result has done: true; later next() calls give { value: undefined, done: true }.

## Code examples

### Lazy infinite sequence with a take helper

```
function* naturals(start = 1) {
  let n = start;
  while (true) yield n++; // never blocks: runs only on demand
}

function* take(count, iterable) {
  if (count <= 0) return;
  for (const value of iterable) {
    yield value;
    if (--count === 0) return; // return() closes the source too
  }
}

function* map(fn, iterable) {
  for (const value of iterable) yield fn(value);
}

const squares = map(n => n * n, naturals());
console.log([...take(5, squares)]);
```

Nothing is computed until spread pulls values, and only five squares are ever produced even though the source is infinite. Composing generators like this avoids intermediate arrays.

### next(value), return() and yield\* delegation

```
function* checkout() {
  const coupon = yield 'Enter coupon';
  try {
    yield `Applied ${coupon}`;
    yield 'Paying...';
  } finally {
    console.log('cleanup ran');
  }
}

const flow = checkout();
console.log(flow.next().value);
console.log(flow.next('SWIGGY50').value);
console.log(flow.return('cancelled'));

class Tree {
  constructor(value, children = []) { this.value = value; this.children = children; }
  *[Symbol.iterator]() {
    yield this.value;
    for (const child of this.children) yield* child; // delegate
  }
}
console.log([...new Tree('a', [new Tree('b'), new Tree('c', [new Tree('d')])])]);
```

The value passed to next becomes the result of the paused yield, and return() ends the generator after running its finally block. yield\* delegates to another iterable, which makes recursive tree traversal a few lines.

## Key points

- Calling a generator function returns an iterator; the body runs only when next() is called.
- yield pauses and emits a value; next(x) resumes and makes the yield expression evaluate to x.
- Generators are iterable, so they work with for...of, spread and destructuring, but only once.
- return() and throw() let the caller end or inject errors, and finally blocks still run.
- yield\* delegates to another iterable or generator.

## Common follow-up questions

- How would you implement a range() function using a generator?
- Why is the value passed to the first next() call ignored?
- How did libraries like co implement async/await on top of generators?
- What is the difference between a generator and an async generator?
- How does breaking out of a for...of loop affect a generator?

## Interview tips

- Explain the state machine in terms of next(), yield and done; interviewers want to hear that execution is suspended, not re-run.
- Show one lazy example (infinite sequence with take) because it proves you understand on-demand evaluation.
- Mention that async/await replaced most generator-based async code, but generators remain the best tool for custom iterables.

## Concepts covered

Generator Function, yield, Iterator Protocol, Lazy Evaluation, yield\*, Coroutines

Previous: [WeakMap and WeakSet](https://www.internhack.in/learn/interview/javascript-interview/js-weakmap-weakset) · Next: [Optional Chaining and Nullish Coalescing](https://www.internhack.in/learn/interview/javascript-interview/js-optional-chaining-nullish) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Currying and Function Composition](https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition)
- [Memoization](https://www.internhack.in/learn/interview/javascript-interview/js-memoization)
- [Property Descriptors and Object.defineProperty](https://www.internhack.in/learn/interview/javascript-interview/js-property-descriptors)
- [Deep Cloning: structuredClone vs JSON](https://www.internhack.in/learn/interview/javascript-interview/js-structuredclone)
- [JavaScript Design Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-design-patterns)
- [Memory Leaks in JavaScript](https://www.internhack.in/learn/interview/javascript-interview/js-memory-leaks)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
