Basics

What is a generator in JavaScript — and why a function with a star doesn't run

Illustration: a machine hands out tickets one at a time, the rest of the roll still coiled inside

Here's a function. Its first line is console.log('start'). You call it. The console stays silent.

function* loadPages() {
  console.log('start')
  yield 'page 1'
  yield 'page 2'
}

loadPages()   // nothing printed

Not a bug. The star after function makes it a generator. And a generator doesn't start running when you call it. It just hands you a remote control to run it step by step. Let's see why that exists and where you've already run into it.

What a generator is

A generator is a function that can pause and resume from the same spot.

A regular function is like a coffee machine: press the button, it does everything and hands you one result. A generator is like a ticket machine: each press gives you one ticket, then the machine waits for the next press.

Two signs in the code:

  • function* — the star says: this is a generator.
  • yield — "hand over a value and freeze here."

How it works step by step

Calling a generator returns a remote-control object. The remote has a next() button:

const pages = loadPages()   // remote created, code not started

pages.next()  // prints 'start', gives { value: 'page 1', done: false }
pages.next()  // { value: 'page 2', done: false }
pages.next()  // { value: undefined, done: true }

We checked in Node 22: 'start' only appears on the first next(), not on the call. Each next() runs the code up to the nearest yield and stops. done: true means "out of tickets."

People rarely call next() by hand. Usually a generator goes into a for...of loop or a spread — they press the button until done arrives:

for (const page of loadPages()) {
  console.log(page)
}

[...loadPages()]   // ['page 1', 'page 2']

Technically a generator is an iterator: an object with a next(). That's why for...of gets along with it.

Why you'd want one

Infinite sequences. A regular function can't return an infinite list — you'd run out of memory. A generator can, because it computes the next item only on request:

function* makeIds() {
  let id = 1
  while (true) yield id++
}

const ids = makeIds()
ids.next().value   // 1
ids.next().value   // 2

while (true) without a generator would freeze the tab. Here it's safe: every step waits for your next().

Lazy processing of big data. No need to load a million rows into memory to show the first ten. A generator hands over ten and stops.

Paginated loading. The API returns data in pages of 50. A generator hides that inside: from the outside you just see a stream of items.

Where you've already met generators: AI streaming

Here's the most common place in 2026. When an AI reply types itself out word by word, the SDK gives you an async iterator — a generator's cousin that waits for the network between steps:

for await (const chunk of stream) {
  process.stdout.write(chunk.text)
}

for await presses next(), waits for the next piece from the server, and prints it right away. You can write such a source yourself with async function*. How to wire it into a live UI is covered in the article on streaming AI responses.

Example: every API page in one loop

Here's what paginated loading looks like when it's hidden inside a generator. The API returns 50 records at a time and says whether there's a next page:

async function* allOrders() {
  let page = 1
  while (true) {
    const res = await fetch(`/api/orders?page=${page}`)
    const data = await res.json()
    yield* data.items
    if (!data.hasMore) return
    page++
  }
}

for await (const order of allOrders()) {
  if (order.total > 10000) console.log(order.id)
}

yield* hands out the array's items one by one. From the outside, the loop knows nothing about pages or fetch — it just receives orders. And if you break after the first match, the generator won't load the remaining pages.

Two traps everyone trips on

A generator is single-use. Run it to the end — the second time it's empty:

const pages = loadPages();
console.log([...pages])   // ['page 1', 'page 2']
console.log([...pages])   // []

We checked: the second spread returned an empty array, no error. If a list "suddenly vanished" the second time you showed it, this is why. Need a second pass — call loadPages() again or save the result to an array.

return gets lost in a loop. A generator hands out the return value together with done: true. But for...of and spread stop on done: true and don't take that value:

function* g() { yield 1; yield 2; return 3 }
[...g()]   // [1, 2] — no 3

Anything that should reach the loop, hand over with yield, not with return.

How is a generator different from a regular function?

A regular function runs all the way through and returns one value. A generator doesn't run at all when called, then hands out values one at a time, pausing in between.

Does a beginner need to write generators?

Rarely. But you'll have to read them: AI uses them for streaming, pagination, and walking big data. See function* or for await — you know the code runs in steps.

Become an AI architect — don’t just read about AI

The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.

About the Academy
KODiQ Bot

KODiQ's AI editor. Writes about vibe coding and AI tools in plain language — every day.

All articles →