Back to Explore
GuideVibeFix editorialUpdated Nov 21, 2026

Don't compute everything up front: JavaScript generators and iterators — function*, yield, and one value at a time

An array has to be computed all at once; a generator hands out one value at a time, only when asked. Following MDN's Iterators and generators, function*, and Generator docs: the next() protocol, function* and yield, for...of consumption, Symbol.iterator, yield* delegation, sending values in with next(x), throw() and return(), and when to use a generator at all — with a 100-mistake breakdown from a fictional cafe order page.

Real photo: a barista in a dark apron pouring steamed milk from a pitcher into a white cup, a heart-shaped latte art pattern forming, an espresso machine behind him

First, the boundary of this guide. The site already has plenty of JavaScript basics guides: loops explain how for, while, and for...of repeat things, functions explain how to write functions, Promises and async explain how to wait for asynchronous results, array methods explain how to work with lists, Map and Set explain how to look things up by name and remove duplicates, and objects and destructuring explain how to take data apart. This guide covers none of those. It covers one thing: the mechanism that hands out one value at a time and only computes it when asked — iterators and generators. The running example is "Greenstone Cafe", the same fictional practice project as before: a small order page for a street-side cafe. Earlier guides used it to show decisions, loops, and reading data; this time it shows pickup numbers: ticket numbers are handed out one at a time, and customers come to collect when their number is called, instead of computing every number for the whole day up front. Everything shown with it — the operations, the code, and the numbers — is invented to explain the technique, not a real record. Every rule about iterators and generators comes from MDN's three official docs, "Iterators and generators", "function*", and "Generator"; the sources are listed in each article's meta information and evidence record. By the end you should be able to do four things: read the { value, done } that next() returns, write function* and yield, consume a generator with for...of and spread syntax, and know when a generator is the right tool and when a plain array is enough. The generators that the loops guide explicitly left out are exactly what this guide covers.

Step 1: First look at the problem — an array has to be computed all at once

The order page has to hand out pickup numbers for today's orders: 1, 2, 3, and so on. Written with an array, every number has to be computed first and put in the array: 200 orders today means computing 200 numbers first; 500 orders tomorrow means computing 500. Nobody has come to collect anything yet, and all the work is already done. Worse is the case where you do not know how many there will be: pickup numbers can in theory keep coming forever, and an array cannot hold "infinitely many". MDN opens the iterator chapter by pointing this out: arrays must be allocated in their entirety, but iterators are consumed only as necessary. That is why iterators can express sequences of unlimited size, such as the integers from 0 to Infinity, while arrays cannot. The word "iterator" sounds grand, but the meaning is small: an object is an iterator when it has a next() method that returns the next value each time it is called, plus a flag saying whether it is finished. A generator is the low-effort way to write an iterator: instead of hand-writing a state machine, you write a function with a star in it, use yield to hand values out one at a time, and JavaScript remembers the state for you. Remember this division of labour for the rest of the guide: the iterator is the rule, and the generator is the low-effort way of following the rule.

Step 2: The iterator protocol — next() gives { value, done } every time

The iterator protocol is a single agreement: an object has a next() method, and every call returns an object with two properties: value, the next value in the sequence, and done, a boolean saying whether the last value has already been consumed. When value appears alongside done, it is the iterator's return value. MDN's example hand-writes a range iterator:

function makeRangeIterator(start = 0, end = Infinity, step = 1) {
  let nextIndex = start;
  let iterationCount = 0;
  const rangeIterator = {
    next() {
      let result;
      if (nextIndex < end) {
        result = { value: nextIndex, done: false };
        nextIndex += step;
        iterationCount++;
        return result;
      }
      return { value: iterationCount, done: true };
    },
  };
  return rangeIterator;
}

const iter = makeRangeIterator(1, 10, 2);
let result = iter.next();
while (!result.done) {
  console.log(result.value); // 1 3 5 7 9
  result = iter.next();
}
console.log("Iterated over sequence of size:", result.value); // [5 numbers returned, that took interval in between: 0 to 10]

Starting at 1, stopping before 10, stepping by 2, it gives 1, 3, 5, 7, 9 — five numbers — and the value returned at the end is 5, the size of the sequence. Note two things. First, an iterator is a consumable: values already taken are never given a second time, and once it is finished, calling next() again just keeps returning { done: true }. MDN's words are "iterating over an iterator is said to consume the iterator, because it is generally only possible to do once". Second, hand-writing an iterator means maintaining its internal state yourself: where nextIndex has reached, how many values have been counted — one wrong step and everything breaks. MDN says right after this that custom iterators are useful, but their creation requires careful programming because of the need to explicitly maintain internal state, and that generator functions provide a powerful alternative. The next section covers that alternative.

Step 3: function* and yield — calling it runs nothing, next() runs one stretch

A generator function is written with function*, and the star is what sets it apart from an ordinary function. Its key behaviour is one sentence: when you call it, not a single line of the function body runs; it only returns a special iterator called a Generator. When you call that Generator's next(), the body runs from the start until the first yield, stops there, and hands out the value after yield; call next() again, and it resumes where it stopped, runs to the next yield, and stops again. MDN's example:

function* generator(i) {
  yield i;
  yield i + 10;
}

const gen = generator(10);
console.log(gen.next().value);
// Expected output: 10

console.log(gen.next().value);
// Expected output: 20

generator(10) computes nothing when called; the first next() runs to the first yield and gives 10; the second next() runs to the second yield and gives 20; a third next(), with the body finished, gives { value: undefined, done: true }. The same generator function can be called many times, and each call returns a new Generator; each Generator runs on its own and does not interfere with the others — but each Generator may only be iterated once, just like the iterator in the previous section. Two more rules for how one ends. First, when the body hits a return, next() returns { value: the returned value, done: true }, and any yield after the return is never reached. MDN's example is yieldAndReturn: the first next() gives { value: "Y", done: false }, the second gives { value: "R", done: true }, the third gives { value: undefined, done: true }, and the "unreachable" yield is never reached. Second, when the body throws an error nobody catches, next() throws that error, the generator finishes, and later next() calls only return { value: undefined, done: true }. My judgement is: think of a generator function as "a function that can pause", where yield is the pause button, next() is the resume button, and where the yields sit decides how many pauses there are and what each one hands out.

Step 4: for...of consumes a generator — and an infinite one needs a break

Hand-writing a next() loop is verbose; in daily use, for...of consumes a generator: it calls next() for you until done is true, and the return value is not picked up by the loop body. MDN's endless ticket-number example shows best what generators are for:

function* idMaker() {
  let index = 0;
  while (true) {
    yield index++;
  }
}

const gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
// …

while (true) in an ordinary function is a dead loop; in a generator function it is not: every yield stops and waits for the next next(), so 0, 1, 2, 3 come out one at a time, forever, without ever freezing. The cafe's pickup numbers are written this way: function* ticketNumbers() starts at 1 and keeps going, and you take as many as have been called, without computing the whole day's numbers in advance. MDN also has an example that computes powers of 2, used with a break:

function* powers(n) {
  // Endless loop to generate
  for (let current = n; ; current *= n) {
    yield current;
  }
}

for (const power of powers(2)) {
  // Controlling generator
  if (power > 32) {
    break;
  }
  console.log(power);
  // 2
  // 4
  // 8
  // 16
  // 32
}

2, 4, 8, 16, 32 come out in order, and at 64 the break stops it. An infinite generator must have a stopping condition, and break is the most common one; forget it, and for...of will run forever and freeze the page. One more detail: for...of never sees the value a generator returns. When the loop ends, the return value is thrown away — to read it, call next() yourself and look at the object from the last call.

Step 5: Iterables and Symbol.iterator — why a plain object cannot be used with for...of

An iterator is an object that hands out values one at a time; an iterable is an object that knows how to hand out values one at a time. An object is iterable if and only if it implements the [Symbol.iterator]() method — that is, it (or one of the objects up its prototype chain) has a property with a Symbol.iterator key. Built-in types such as Array, Map, Set, and String are all iterable, because their prototype objects all have this method; a plain object is not, so using for...of directly on a plain object throws. MDN's example builds an iterable by hand:

const myIterable = {
  *[Symbol.iterator]() {
    yield 1;
    yield 2;
    yield 3;
  },
};

for (const value of myIterable) {
  console.log(value);
}

// 1
// 2
// 3

[...myIterable]; // [1, 2, 3]

The star in front of the method name means "this is a generator method", and whatever the body yields is what for...of receives. Spread syntax works the same way, because it also wants an iterable, so [...myIterable] gives [1, 2, 3]. A generator is itself iterable, but its [Symbol.iterator]() returns itself, so it can only run once: in MDN's example, makeIterator yields 1 and 2, iter[Symbol.iterator]() === iter is true, the first for...of pass gives 1 and 2, and the second gives nothing at all. To make it run many times, replace [Symbol.iterator] with a method that returns a new generator each time; in MDN's example the rewritten version yields 2, 1. The cafe example: the order list is paged with a generator, 3 orders per page, and 10 orders split into 4 pages: [1, 2, 3], [4, 5, 6], [7, 8, 9], [10]. The number of pages is never computed in advance; for...of stops on its own when there are no pages left. My judgement is: to tell whether something works with for...of, do not memorize a list — just ask one question, "does it have [Symbol.iterator]()?" If yes, it works; if no, it does not. Arrays, strings, Maps, and Sets have it; plain objects do not.

Step 6: yield* delegation — handing the work to another generator

When one generator wants to hand work to another generator, use yield*, and the star must not be left out. MDN's example is two generators working in relay:

function* anotherGenerator(i) {
  yield i + 1;
  yield i + 2;
  yield i + 3;
}

function* generator(i) {
  yield i;
  yield* anotherGenerator(i);
  yield i + 10;
}

const gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20

It yields 10 itself, hands 11, 12, 13 to anotherGenerator, then yields 20 itself. yield* can also be followed directly by an iterable such as an array: yield* ["a", "b", "c"] yields "a", "b", and "c" in order, and the first next() gives { value: "a", done: false }. The easiest mistake is dropping the star: yield anotherGenerator(i) without the star yields the Generator object itself, not the values inside it, so whoever receives it gets an object, not 11, 12, 13. The cafe example: drinks come off two lines, hot drinks in one queue and cold drinks in another. The main generator yields* the hot drinks first, then yields* the cold drinks, and the pickup screen shows one complete serving order, without merging the two queues into one big array first. My judgement is: read yield* as "hand out, one at a time, every item of the iterable that follows", and read yield as "hand out this one thing". The two symbols differ by one star, and their meanings differ by a whole layer.

Step 7: next(x) sends a value in — and the first value sent is ignored

next() does not only take values out; it can also send a value in. The value passed to next() becomes the value of the yield expression the generator is currently paused at. MDN's words are "the next() method also accepts a value, which can be used to modify the internal state of the generator. A value passed to next() will be received by yield." But there is one iron rule: a value passed to the first invocation of next() is always ignored, because on the first call the body has not reached any yield yet, so nobody is waiting for the value. MDN's Fibonacci example pushes this mechanism to its limit:

function* fibonacci() {
  let current = 0;
  let next = 1;
  while (true) {
    const reset = yield current;
    [current, next] = [next, next + current];
    if (reset) {
      current = 0;
      next = 1;
    }
  }
}

const sequence = fibonacci();
console.log(sequence.next().value); // 0
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
console.log(sequence.next().value); // 3
console.log(sequence.next().value); // 5
console.log(sequence.next().value); // 8
console.log(sequence.next(true).value); // 0
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2

0, 1, 1, 2, 3, 5, 8 come out in order; one call of next(true) restarts the generator, and 0, 1, 1, 2 come around again. MDN has a plainer example, logGenerator: each time the body reaches a yield it prints a line, next("pretzel") makes it print "1 pretzel", next("california") prints "2 california", and next("mayonnaise") prints "3 mayonnaise" — the value sent in appears unchanged in the printout. The cafe does not need this mechanism much. My judgement is: beginners do not need to worry about sending values in. Treat "yield hands out, next() hands in" as an advanced use, remember that the first value sent is ignored, and never pass a critical argument in the first next(). The everyday tools are next() with no argument and for...of.

Step 8: throw() and return() — ending a generator from the outside

Besides next(), a generator has two methods for intervening from the outside. throw() means "pretend an error was thrown at the exact spot where the generator is currently paused": if the generator body has a try...catch that catches it, the catch block can keep yielding values; if nothing catches it, the error travels out through the throw() call, the generator finishes, and later next() calls only give { value: undefined, done: true }. return() means "pretend a return was written at the paused spot": the generator ends at once, this return() call gives back { value: the value you passed, done: true }, and any finally block in the body is guaranteed to run, so it can clean up things like resources that were opened. MDN's words are that the return() method returns the given value and finishes the generator itself, and that combined with a try...finally block it lets the generator perform cleanup tasks. The cafe example: the pickup-screen generator is handing out numbers one at a time, the shop is closing, and it has to stop early — calling return() does it, and the "close the pickup screen" step in finally is guaranteed to run, never skipped. Two more hard facts belong here. First, generator functions have no arrow-function counterpart — function* is the only way to write one. Second, a generator function cannot be used with new: new f() throws a TypeError saying it is not a constructor. Calling a generator function gives you a Generator object, not an instance — do not mix the two up.

Step 9: When to use a generator, and when not to

Generators fit three jobs best. First, computing values on demand: the data is large or endless, so compute one at a time and keep only the current one in memory — pickup numbers, pages, or reading a large file line by line. Second, gathering complicated loop state into one function: hand-writing an iterator means maintaining indexes and counters yourself, while a generator function just needs a for loop and a few yields, with the function remembering the state. Third, defining iterables: to make a custom object work with for...of and spread, hang a *[Symbol.iterator]() method on it and yield a few times, exactly as in the Step 5 example. The cases where a generator does not fit are worth remembering too. When the list is small to begin with and computing it all at once costs nothing, use an array and a loop directly — do not reach for a generator just to use one. For asynchronous flows, the simpler async function and Promise model now handles the job; MDN says so plainly on the function* page: generators used to be a paradigm for asynchronous programming, but nowadays this use case is solved with the simpler async functions model and the Promise object, while generators are still useful for tasks such as defining iterators. That is also the boundary between this guide and the Promise and async guide: that one explains "how to wait for one asynchronous result", this one explains "how to hand out one value at a time", and the two do not overlap. One more rule of thumb: if you catch yourself writing yields in a generator only to hand out the contents of an array one by one, stop and ask whether for...of over the array directly would be simpler. Nine times out of ten, it would.

Step 10: Seven traps and a checklist

Finally, the seven traps beginners hit most, which are also where the chart's numbers come from. First, calling a generator function and assuming the code runs at once — in fact not a single line runs until the first next(). Second, using the same generator a second time and assuming it can run again — in fact it can only run once, and a fresh run needs a new Generator from calling the function again. Third, forgetting to write yield, so the function runs through in one go and gives only a single return value, with the star wasted. Fourth, reading only .value from what next() returns and forgetting done, so you keep reading after the generator has finished and treat undefined as a real value. Fifth, passing a value to the first next() and assuming it gets in — in fact the first value passed is always ignored. Sixth, forgetting the star in yield*, so you yield a single Generator object, and whoever receives it gets an object instead of values. Seventh, calling next() after the generator is finished and expecting an error — in fact it just keeps quietly returning { value: undefined, done: true }. Run through the checklist: does the generator function have its star, and does it have a yield; are you consuming it with for...of or a hand-written next() loop, and if for...of, does it matter that the return value is thrown away; does an infinite generator have a break or another stopping condition; does [Symbol.iterator] return itself or a new generator, and is something that can only run once being run a second time; did you pass a value to the very first next() call.

One more point that is easy to miss: the value a generator returns is not free — only a hand-written next() loop can see it. for...of stops as soon as done is true, and the return value is already thrown away by then; the loop body never sees it. In the hand-written range iterator example, the last next() returns a value of 5, the size of the sequence, and only a hand-written while loop can read that 5 — swap in for...of and it is gone. My judgement is: a return value is only good for "telling the caller something on the side", such as how many values were handed out, and the caller reads it with a hand-written loop if it wants it. If the return value is data you genuinely need, do not put it in a return — yield it one more time instead, so for...of can receive it too. A matching detail: after a generator has finished, calling next() again always gives { value: undefined, done: true }, never an error and never the previous value, so do not write loop tests that expect it to change.

Bar chart: causes behind 100 generator mistakes on the order page in one month

The chart above shows the fictional Greenstone Cafe order page's 100 generator mistakes in one month, broken down by cause: calling a generator function and assuming the code runs at once, 24 times; using the same generator a second time and assuming it can run again, 18 times; forgetting to write yield, so the function runs through in one go and gives only one value, 16 times; reading only .value from what next() returns and forgetting done, 12 times; passing a value to the first next() and assuming it gets in, 11 times; forgetting the star in yield*, so only a Generator object is produced, 10 times; calling next() after the generator is finished and expecting an error, 9 times. 24 + 18 + 16 + 12 + 11 + 10 + 9 = 100, the books balance. The top three causes together are almost sixty percent, and all of them are the same misunderstanding: treating a generator like an ordinary function. An ordinary function runs when called and can be called again when finished; a generator does not run when called, and cannot run again once finished. Every category in the chart maps to a step in this guide: the first to Step 3, the second to Steps 3 and 5, the third to Step 3, the fourth to Step 2, the fifth to Step 7, the sixth to Step 6, and the seventh to Steps 3 and 8. The next time a generator misbehaves, check in that order: first whether next() was ever called after the call, then whether the same generator was run a second time — two steps usually locate it.

Looking back at the four things this guide promised: next() returns { value, done } each time, and done being true means it is finished; function* does not run when called, yield is the pause button and next() is the resume button; for...of and spread consume a generator automatically, but the return value and a second pass are both out of reach; and generators fit computing values on demand, endless sequences, and custom iterables, while a simple list should just use an array, not a forced generator. The for...of from the loops guide changes roles here: there it was the workhorse for walking arrays, here it is the workhorse for consuming generators — the same syntax, only the data source changes. Once you finish this guide, rewrite the order page's pickup numbers as a generator: numbers are handed out one at a time, only as many as have been called are computed, there is no need to compute the whole day's numbers in advance, and the code is shorter than the array version.

Views 3Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: two baristas working side by side behind a cafe counter, one pouring steamed milk into a white cup, the other operating an espresso machine
Guide
Don't let the main thread carry it all: Web Workers, handing heavy work to another thread

The main thread has to draw the page and do the accounts, so it freezes the moment the work gets heavy. A worker is another thread in another global context, and the two sides talk only through messages. Following MDN's Using Web Workers and Worker docs: new Worker, postMessage and onmessage, structured-clone copying, what a worker can and cannot do, onerror and terminate(), SharedWorker, and transferable zero-copy — with a 100-mistake breakdown from a fictional cafe order page.

Tool TipsFrontend EngineeringLearning & Career
Real photo: a black twin-bell alarm clock on a wooden table in warm morning light, the dial showing about twenty-eight minutes past two
Guide
Not now — when the time comes: JavaScript timers setTimeout and setInterval

setTimeout handles once, setInterval handles repeatedly — but delay only promises "at least this long": 0 is not immediate, background tabs run even later, and anything over 2147483647 overflows. Following MDN's setTimeout and setInterval docs: async return, argument passing, the delay rules, the 4 ms nesting clamp, clearTimeout and clearInterval, recursive setTimeout, lost this, and string arguments — with a 100-mistake breakdown from a fictional cafe order page.

Tool TipsFrontend EngineeringLearning & Career
Real photo: a hand-lettered chalkboard coffee menu on a brick wall, listing six drinks with prices from Espresso 2.95 to Latte 4.25
Guide
Stop missing data from crashing your page: JavaScript optional chaining ?. and nullish coalescing ??, explained plainly

One missing layer in your data can blank the whole order page. Following MDN's Optional chaining, Nullish coalescing, and Logical nullish assignment docs: the three forms of ?., short-circuiting, optional calls and bracket access, ?? vs || on 0 and empty strings, the ?. + ?? combination, the ban on mixing ?? with || and &&, and ??= defaults — with a 100-mistake breakdown from a fictional cafe order page.

Tool TipsFrontend EngineeringLearning & Career