Generators (function*, yield)

Published by Brayan K

In the last lesson you wrote Symbol.iterator and next() by hand. Generators let you produce the exact same iterators with a fraction of the code — and a superpower normal functions don't have: the ability to pause partway through and resume later.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Calling the generator creates a paused object

A generator function returns a generator object. Its body begins when you request the first result with next, and later requests resume after the last yield. The generator object already implements the contracts explained in Iterators & Iterables.

"use strict";
function* labels() {
  console.log("body started");
  yield "A17";
  console.log("body resumed");
  yield "B24";
}
const cursor = labels(); // Construct the cursor without entering the body.
console.log("created");
const first = cursor.next(); // Run until the first yield.
console.log(first.value, first.done);
const second = cursor.next(); // Continue after that yield.
console.log(second.value, second.done);
const end = cursor.next();
console.log(end.value, end.done);

// ✅ Expected output:
// created
// body started
// A17 false
// body resumed
// B24 false
// undefined true

Each request can run ordinary synchronous work before it reaches a yield. A generator is not a background thread and does not automatically let the browser paint between its statements.

The star changes which syntax the function body may use

Yield belongs to a generator body. It does not turn an ordinary function into a generator by appearing inside it. The examples use explicit strict mode so this syntax error is checked consistently in the editor and Node.

"use strict";
function labels() {
  yield "A17";
}
console.log(labels());

// ✅ Expected error:
// SyntaxError: Unexpected strict mode reserved word

Use function* for the function that directly contains yield. A nested ordinary callback does not inherit permission to yield from a surrounding generator. Functions owns ordinary function calls and returns.

Body validation is deferred until the body runs

An argument check placed inside a generator body runs on the first next call, not merely when the generator object is created. Put a check in an ordinary wrapper if your API needs to reject the call immediately.

"use strict";
function* ticketNumbers(start) {
  if (!Number.isSafeInteger(start) || start < 1) {
    throw new RangeError("start must be a positive safe integer");
  }
  yield start;
}
const cursor = ticketNumbers(0);
console.log("cursor created");
cursor.next();

// ✅ Expected output:
// cursor created

// ✅ Expected error:
// RangeError: start must be a positive safe integer

The displayed creation message identifies where execution reached before the error. Error Handling owns catching failures; the timing here follows the generator’s suspended body.

Yield supplies a sequence value; return supplies completion

Yield pauses and reports done false. Return finishes ordinary generator execution and reports done true with its return value. For...of, spread and Array.from collect yielded values, not the final completion value.

"use strict";
function* labels() {
  yield "A17";
  return "finished";
}
const cursor = labels();
for (let index = 0; index < 3; index++) {
  const result = cursor.next();
  console.log(result.value, result.done);
}
console.log(JSON.stringify([...labels()]));

// ✅ Expected output:
// A17 false
// finished true
// undefined true
// ["A17"]

After completion, calling next again does not replay the return value or restart the body. Call the generator function again when you need a new traversal.

"use strict";
function* labels() {
  yield "A17";
  yield "B24";
}
const cursor = labels();
console.log(cursor[Symbol.iterator]() === cursor);
console.log(JSON.stringify([...cursor]));
console.log(JSON.stringify([...cursor]));
console.log(JSON.stringify([...labels()]));

// ✅ Expected output:
// true
// ["A17","B24"]
// []
// ["A17","B24"]

A next argument answers the yield that was already paused

The value passed to next becomes the result of the currently suspended yield expression. The first next call has no earlier yield waiting for an answer, so its argument is ignored. Use generator parameters for initial inputs.

"use strict";
function* request(prefix) {
  const item = yield "Which item?";
  yield prefix + item;
  return "complete";
}
const cursor = request("Item ");
const first = cursor.next("ignored");
console.log(first.value, first.done);
const second = cursor.next("A17");
console.log(second.value, second.done);
const end = cursor.next();
console.log(end.value, end.done);

// ✅ Expected output:
// Which item? false
// Item A17 false
// complete true

Do not read the outgoing yielded value as the incoming answer. They travel in opposite directions across two different next calls. The generator’s local item binding is assigned only when that first yield resumes.

Yielding an iterable is different from delegating to it

Yield treats its expression as one value. Yield* delegates to an iterable and exposes the values from its traversal. This distinction matters when the value is an array: one array value is different from its separate elements.

"use strict";
function* nested() {
  yield ["A17", "B24"];
}
function* delegated() {
  yield* ["A17", "B24"];
}
console.log(JSON.stringify([...nested()]));
console.log(JSON.stringify([...delegated()]));

// ✅ Expected output:
// [["A17","B24"]]
// ["A17","B24"]
"use strict";
function* child() {
  yield "A17";
  return "child complete";
}
function* parent() {
  const completion = yield* child();
  yield completion;
}
console.log(JSON.stringify([...child()]));
console.log(JSON.stringify([...parent()]));

// ✅ Expected output:
// ["A17"]
// ["A17","child complete"]

The child completion is the result of the yield* expression. The parent in this example deliberately yields it as a new sequence value; delegation alone would not add that completion value as an element.

Breaking a generator loop runs entered cleanup

A for...of break calls the generator’s return method. If execution has entered a try/finally, that causes the finally block to run. This makes cleanup observable without pretending that simply losing interest in a cursor automatically closes it.

"use strict";
function* labels() {
  try {
    yield "A17";
    yield "B24";
  } finally {
    console.log("cleanup");
  }
}
const cursor = labels();
for (const item of cursor) {
  console.log(item);
  break;
}
console.log(cursor.next().done);

// ✅ Expected output:
// A17
// cleanup
// true
"use strict";
function* labels() {
  try {
    console.log("entered");
    yield "A17";
    yield "B24";
  } finally {
    console.log("cleanup");
  }
}
const started = labels();
console.log(started.next().value);
console.log("still paused");
const closed = started.return("stopped");
console.log(closed.value, closed.done);
const untouched = labels();
console.log(untouched.return("never started").done);

// ✅ Expected output:
// entered
// A17
// still paused
// cleanup
// stopped true
// true

The untouched generator never entered its body, so its finally block was never entered either. Resource setup and teardown should follow the actual execution lifecycle. A generator’s local variables persist while it is paused; Closures and Scope owns broader retained-binding patterns.

A finally block that yields can delay completion

Return requests completion, but a finally block can run first. If that block itself yields, the returned result can still have done false. Keep cleanup straightforward when callers expect closing to finish immediately, and inspect the actual result when experimenting with resumable cleanup.

"use strict";
function* labels() {
  try {
    yield "A17";
  } finally {
    yield "cleanup checkpoint";
  }
}
const cursor = labels();
console.log(cursor.next().value);
const closing = cursor.return("stopped");
console.log(closing.value, closing.done);
const finished = cursor.next();
console.log(finished.value, finished.done);

// ✅ Expected output:
// A17
// cleanup checkpoint false
// stopped true

The prior cleanup examples only logged inside finally, so they did not suspend during closing. This boundary is why “return always finishes immediately” would be too broad.

Only requested work runs, but each request still needs to finish

Laziness means later work can remain unperformed. It does not guarantee a small running time for next, and retaining all produced values still costs storage. In the browser editor, Console mode provides Stop for a stuck computation; generation alone is not an interruption mechanism.

"use strict";
let produced = 0;
function* values() {
  for (let index = 0; index < 4; index++) {
    produced += 1;
    yield index * 2;
  }
}
const cursor = values();
console.log("before", produced);
console.log(cursor.next().value);
console.log(cursor.next().value);
console.log("after two requests", produced);
cursor.return();

// ✅ Expected output:
// before 0
// 0
// 2
// after two requests 2

An unbounded generator can be useful with a consumer that stops. Spreading an unbounded source would try to consume everything. Async Iterators & for-await-of owns asynchronous iteration; an ordinary generator here does not wait for external work.

Complete a generator and request its first values

Use the literal hints to mark the function as a generator, produce a value and request its first result. The loop has a finite upper bound so the example remains bounded even if it is later collected into an array.

"use strict";
function___ ticketNumbers() {
  for (let number = 10; number <= 12; number++) {
    ___ number;
  }
}
const cursor = ticketNumbers();
console.log(cursor.___().value);
console.log(cursor.next().value);
// 👉 replace ___ with *
// 👉 replace ___ with yield
// 👉 replace ___ with next

// ✅ Expected output:
// 10
// 11

Take exactly the requested number of source values

Write a take(iterable, limit) generator. When consumed, it must reject a negative or unsafe-integer limit with RangeError. A zero limit must not request any source value. For a positive limit, yield at most that many values, stop without requesting one extra value, and allow early closing to reach the source. Check an unbounded source with limit three, a zero limit and a source shorter than the limit.

"use strict";
function* take(iterable, limit) {
  if (!Number.isSafeInteger(limit) || limit < 0) {
    throw new RangeError("limit must be a nonnegative safe integer");
  }
  if (limit === 0) return;
  let taken = 0;
  for (const value of iterable) {
    yield value;
    taken += 1;
    if (taken === limit) return;
  }
}
let produced = 0;
let closed = false;
function* ids() {
  try {
    let id = 1;
    while (true) {
      produced += 1;
      yield id++;
    }
  } finally {
    closed = true;
  }
}
console.log(JSON.stringify([...take(ids(), 3)]));
console.log("produced", produced, "closed", closed);
produced = 0;
closed = false;
console.log(JSON.stringify([...take(ids(), 0)]));
console.log("produced", produced, "closed", closed);
console.log(JSON.stringify([...take(["A17", "B24"], 4)]));
try {
  console.log([...take([], -1)]);
} catch (error) {
  console.log(error.name + ": " + error.message);
}

// ✅ Expected output:
// [1,2,3]
// produced 3 closed true
// []
// produced 0 closed false
// ["A17","B24"]
// RangeError: limit must be a nonnegative safe integer

The zero check comes before the source loop. After each resumed yield, the limit is checked before another source value is requested. The three-value spread fully consumes take, causing its return and the source’s entered cleanup. A caller that pauses take after a yield still owns that paused cursor and can close it with return.

References: MDN documents generator functions, next, return and yield* delegation.

Practice quiz

What does this complete program print? "use strict"; function* items() { console.log("body"); yield 1; } const cursor = items(); console.log("created"); console.log(cursor.next().value);

  • created body 1
  • body created 1
  • created 1 body
  • created undefined

Answer: created body 1. The body begins on next, after construction has returned the cursor.

What does this complete program print? "use strict"; function* items() { yield 1; return 9; } console.log(JSON.stringify([...items()]));

  • [1,9]
  • [1]
  • [9]
  • []

Answer: [1]. Spread collects yielded values and omits the completion value.

What does this complete program print? "use strict"; function* items() { yield 1; yield 2; } const cursor = items(); cursor.next(); console.log(JSON.stringify([...cursor])); console.log(JSON.stringify([...cursor]));

  • [1,2] [1,2]
  • [2] [2]
  • [2] []
  • [1,2] []

Answer: [2] []. The first next consumes one value, and the first spread consumes the remainder.

What does this complete program print? "use strict"; function* ask() { const answer = yield "question"; return answer; } const cursor = ask(); console.log(cursor.next("ignored").value); const result = cursor.next("A17"); console.log(result.value, result.done);

  • ignored A17 true
  • question ignored true
  • question A17 false
  • question A17 true

Answer: question A17 true. The first argument is ignored; the later argument supplies the paused yield expression.

What does this complete program print? "use strict"; function* a() { yield [1, 2]; } function* b() { yield* [1, 2]; } console.log(JSON.stringify([...a()])); console.log(JSON.stringify([...b()]));

  • [[1,2]] [1,2]
  • [1,2] [1,2]
  • [[1,2]] [[1,2]]
  • [1,2] [[1,2]]

Answer: [[1,2]] [1,2]. Yield emits one array value, while yield* emits the array’s individual values.

What does this complete program print? "use strict"; let cleaned = false; function* items() { try { yield 1; yield 2; } finally { cleaned = true; } } const cursor = items(); for (const value of cursor) break; console.log(cleaned, cursor.next().done);

  • false false
  • true true
  • false true
  • true false

Answer: true true. Breaking a started generator loop closes it and runs this non-yielding finally block.

What does this complete program print? "use strict"; let entered = false; function* items() { entered = true; yield 1; } const cursor = items(); cursor.return(); console.log(entered, cursor.next().done);

  • true true
  • false false
  • false true
  • true false

Answer: false true. Returning before the first next closes the untouched generator without entering its body.

What does this complete program print? "use strict"; function* items() { try { yield 1; } finally { yield 2; } } const cursor = items(); cursor.next(); const result = cursor.return(9); console.log(result.value, result.done);

  • 9 true
  • 2 true
  • undefined true
  • 2 false

Answer: 2 false. The finally block yields before the pending return completes, so this result is not done yet.

Continue this course

Related lessons