# Generators & Iterators

> Learn how to write functions that can pause their own execution mid-way through, yielding values one at a time on demand.

Subject: JavaScript | Lesson 49 of 63 | 7 min read
Interactive lesson: https://codewithanimation.in/javascript/generators-and-iterators
Previous: [Symbols & Well-Known Symbols](https://codewithanimation.in/javascript/symbols-and-well-knowns.md) | Next: [Proxy & Reflect](https://codewithanimation.in/javascript/proxy-and-reflect.md)

## The Pausable Function

A standard JavaScript function runs from top to bottom, without stopping, until it hits a `return` statement or the end of the block.

**Generators** are special functions (declared with an asterisk `function*`) that can be paused in the middle of execution and resumed later. They do this using the `yield` keyword.

## Lazy Evaluation

Why would you want to pause a function?

Imagine you need to generate a sequence of 1,000,000 unique IDs. If a normal function did this, it would lock up the browser while it calculated and stored all 1,000,000 IDs in memory at once.

A Generator can generate exactly *one* ID, `yield` it to the caller, and then go to sleep. It only generates the next ID when the caller explicitly asks for it. This is called 'lazy evaluation' and is incredibly memory efficient.

## Iterators and next()

When you call a generator function, it doesn't run the code inside. Instead, it returns an **Iterator** object.

```javascript
function* counter() {
  yield 1;
  yield 2;
}
const gen = counter();
```

To actually run the code, you must call `gen.next()`. The function wakes up, runs until it hits the first `yield 1`, and then pauses. `gen.next()` returns an object: `{ value: 1, done: false }`.

If you call `gen.next()` again, it resumes where it left off, hits `yield 2`, and returns `{ value: 2, done: false }`. Calling it a third time returns `{ value: undefined, done: true }`.

## Common mistake: Two-Way Communication

Generators aren't just one-way data producers. You can actually send data *back* into the generator by passing an argument into `.next(value)`.

The value you pass in becomes the evaluated result of the `yield` expression that the generator is currently paused on. This allows for complex ping-pong data flows between the caller and the generator.

## Tip: for...of Compatibility

Because generators return standard Iterators, they are perfectly compatible with `for...of` loops and the spread operator `[...]`. A `for...of` loop will automatically call `.next()` over and over until `done: true` is reached!

## Try it: The Yield Pipeline

Study the architecture diagram below. It illustrates the exact mechanical relationship between the Generator code, the Iterator object, and the flow of `.next()` calls pulling values from `yield` statements.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/generators-and-iterators

## Check yourself

### Question 1

What does calling a generator function like `myGenerator()` immediately return?

- A. An Iterator object.
- B. The first yielded value.
- C. undefined

Correct answer: A

A generator function does not execute its body upon invocation. It acts as a factory that returns a paused Iterator.

- Why not B: Incorrect. You must call `.next()` on the returned Iterator to get the first value.
- Why not C: Incorrect. It returns an active Iterator.

### Question 2

What is the shape of the object returned when you call `.next()` on an iterator?

- A. { value: any, done: boolean }
- B. { result: any, isFinished: boolean }
- C. It just returns the raw value directly.

Correct answer: A

The Iterator Protocol in JavaScript requires iterators to return an object with a `value` property (the yielded data) and a `done` property (a boolean indicating if the sequence has finished).

- Why not B: Incorrect keys. The spec strictly requires `value` and `done`.
- Why not C: Incorrect. It wraps it in an object so it can communicate the `done` status.

### Question 3

How can a Generator be highly memory-efficient when working with massive datasets?

- A. It uses lazy evaluation, only computing and keeping one value in memory at a time.
- B. It automatically compresses the data it returns.
- C. It offloads the calculation to a Web Worker.

Correct answer: A

If you need an array of a million numbers, a normal function creates an array of a million items in RAM. A generator only ever holds one number in RAM, producing the next one on demand.

- Why not B: Incorrect. Generators do not compress data.
- Why not C: Incorrect. Generators run on the main thread like normal functions.

## Remember this

- Generators are declared with `function*` and can pause execution using `yield`.
- Calling a generator function returns a paused Iterator object, it does not run the code inside.
- Use `.next()` to wake the generator up and pull the next value.
- `.next()` returns an object shaped like `{ value: data, done: boolean }`.
- Generators are excellent for memory-efficient lazy evaluation and infinite sequences.
