1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Generators Explained: yield, next() and 10 Examples

JavaScript generators are functions that can pause at yield and resume later, producing values one at a time. Learn how next() drives them, infinite and lazy sequences, two-way communication, yield*, cleanup with return(), async generators for paged APIs, and what they cost in speed, all run in Node.js.

9 min read
JavaScript generators explained: yield, next and 10 examples

Key takeaways

  • JavaScript generators are declared with function* and pause at each yield.
  • Calling one runs no code; each next() runs until the next yield and returns { value, done }.
  • They make infinite and lazy sequences easy: our pipeline squared, filtered and took 5 items from an endless stream.
  • They are slower than plain loops for raw number crunching (70.4 ms vs 3.8 ms for a million items), so use them for clarity and laziness, not speed.

Most functions run from top to bottom and return once. A generator can stop halfway, hand a value to its caller, and continue later exactly where it left off, keeping all its local variables. That one ability makes JavaScript generators the cleanest tool for custom iterators, infinite sequences, lazy data pipelines, tree traversal and paging through APIs.

All ten examples ran in Node.js v24.22.1 as an ES module, and the output is shown as printed. Generators work the same way in every modern browser. If iterators are new, our array methods guide covers the related for...of basics.

What is a generator in JavaScript?

A generator function is declared with an asterisk, function*. Calling it does not run its body. Instead it returns a generator object, which is an iterator: it has a next() method, and it can be used with for...of, spread syntax and destructuring. Each next() call resumes the function until it reaches yield, which pauses it and passes out a value.

Example 1: pausing and resuming with yield

function* count3() {
  console.log("  start");
  yield 1;
  console.log("  after 1");
  yield 2;
  yield 3;
  return "done";
}

const g = count3();
console.log("created, nothing ran yet");
console.log(g.next());   // logs "start", then { value: 1, done: false }
console.log(g.next());   // logs "after 1", then { value: 2, done: false }
console.log(g.next());   // { value: 3, done: false }
console.log(g.next());   // { value: 'done', done: true }
console.log(g.next());   // { value: undefined, done: true }

Our run printed “created, nothing ran yet” before “start”, proving the body only begins on the first next(). The return value appears once with done: true; after that, every call returns undefined.

Example 2: spread and for…of

console.log([...count3()].join(","));   // 1,2,3

Spread and for...of call next() for you until done is true. Note that the return value, "done", is not included: iteration ignores it and only collects yielded values. If you need the final value, call next() manually or use yield*, shown in example 6.

Example 3: infinite sequences

function* ids() {
  let i = 1;
  while (true) yield i++;
}
const it = ids();
console.log(it.next().value, it.next().value, it.next().value);   // 1 2 3

A while (true) loop would normally freeze your program, but here each yield pauses it, so values are produced only on demand. This is handy for ID generators, pagination cursors and simulations. Never spread an infinite generator, though: [...ids()] would run forever.

Example 4: lazy pipelines

function* take(n, src)     { for (const x of src) { if (n-- <= 0) return; yield x; } }
function* map(f, src)      { for (const x of src) yield f(x); }
function* filter(p, src)   { for (const x of src) if (p(x)) yield x; }

console.log([...take(5, filter(x => x % 3 === 0, map(x => x * x, ids())))]);
// [ 9, 36, 81, 144, 225 ]

Array methods like map and filter build a full new array at every step. Generator pipelines pass one value at a time through all stages, so they work on infinite inputs and use constant memory. Here each number is squared, checked for divisibility by 3, and the pipeline stops after five results, without ever creating a big array.

Example 5: sending values into a generator

function* conv() {
  const name = yield "What is your name?";
  const age = yield `Hi ${name}, age?`;
  return `${name} is ${age}`;
}
const c = conv();
console.log(c.next().value, "|", c.next("Asha").value, "|", c.next(30).value);
// What is your name? | Hi Asha, age? | Asha is 30

The argument of next(value) becomes the result of the paused yield expression. The first next() only starts the generator, so a value passed to it is ignored. This two-way flow is how libraries built async control flow on generators before async/await arrived, and it still powers state machines and step-by-step wizards. The strings use template literals.

Example 6: delegating with yield*

function* inner() { yield "a"; yield "b"; return "inner-result"; }
function* outer() {
  const r = yield* inner();
  yield `got ${r}`;
  yield* [1, 2];
}
console.log([...outer()]);   // [ 'a', 'b', 'got inner-result', 1, 2 ]

yield* hands control to another iterable until it finishes, passing its values straight through. The expression itself evaluates to the inner generator’s return value, which is how outer captured "inner-result". It also works with any iterable, such as arrays, strings, Maps and Sets.

Example 7: cleanup with finally and return()

function* withCleanup() {
  try { yield 1; yield 2; yield 3; }
  finally { console.log("  cleanup ran"); }
}

for (const x of withCleanup()) { if (x === 2) break; }   // logs "cleanup ran"

const w = withCleanup();
w.next();
console.log(w.return(99));   // logs "cleanup ran", then { value: 99, done: true }

Breaking out of a for...of loop automatically calls the generator’s return() method, which runs any finally block. You can also call return(value) yourself to stop a generator early. Use this to close files, release locks or cancel timers when the consumer stops early.

Example 8: throwing errors into a generator

function* guarded() {
  while (true) {
    try { yield "ok"; }
    catch (e) { console.log("  caught inside:", e.message); yield "recovered"; }
  }
}
const gd = guarded();
gd.next();
console.log(gd.throw(new Error("boom")).value);
// logs "caught inside: boom", then recovered

throw(error) raises the error at the paused yield, as if that line had thrown. The generator can catch it and continue, or let it propagate to the caller. Combined with example 5, this lets a generator act like a small coroutine that both receives data and handles failures.

Example 9: making objects iterable

class Range {
  constructor(a, b) { this.a = a; this.b = b; }
  *[Symbol.iterator]() { for (let i = this.a; i < this.b; i++) yield i; }
}
console.log([...new Range(3, 7)]);   // [ 3, 4, 5, 6 ]

const tree = { v: 1, kids: [{ v: 2, kids: [{ v: 4, kids: [] }] }, { v: 3, kids: [] }] };
function* walk(n) { yield n.v; for (const k of n.kids) yield* walk(k); }
console.log([...walk(tree)]);   // [ 1, 2, 4, 3 ]

Writing an iterator by hand needs an object with next() and careful state. A generator method on Symbol.iterator does it in one line, and any class becomes usable with for...of and spread; see our JavaScript classes guide. Combining recursion with yield* gives a depth-first tree walk that produces nodes lazily.

Example 10: async generators for paged APIs

async function* pages() {
  for (let p = 1; p <= 3; p++) {
    await new Promise(r => setTimeout(r, 5));   // stand-in for fetch(`/api?page=${p}`)
    yield { page: p, items: [p * 10, p * 10 + 1] };
  }
}
const all = [];
for await (const pg of pages()) all.push(...pg.items);
console.log(all);   // [ 10, 11, 20, 21, 30, 31 ]

An async function* can await inside and is consumed with for await...of. It is the natural way to stream paginated API results, read a file chunk by chunk, or process messages as they arrive. The consumer code stays a simple loop, and the next page is requested only when the loop asks for it. We simulated the network with a timer; see the fetch API guide for real requests.

Generators are single use

const g2 = count3();
console.log([...g2].length, [...g2].length);   // 3 0

A generator object is exhausted after one pass; the second spread got nothing. If you need to iterate again, call the generator function again, or make your object iterable with Symbol.iterator as in example 9, which returns a fresh generator each time.

Tip: pass around the generator function or an iterable object, not a generator instance, when several consumers need the same sequence.

Iterator helpers

ids().filter(x => x % 2).map(x => x * 10).take(3).toArray();
// [ 10, 30, 50 ]

Recent JavaScript engines, including Node.js 24, support iterator helpers: map, filter, take, drop, flatMap, reduce and toArray directly on iterators. They do the same lazy work as our hand-written pipeline in example 4 with less code. Check browser support before relying on them in front-end code.

Performance: generators vs loops vs arrays

Summing 1,000,000 numbers Time
Generator pipeline (take over ids()) 70.4 ms
Plain for loop 3.8 ms
Build an array, then for...of 71.0 ms

Each next() call and result object has overhead, so a generator was about 18 times slower than a plain counting loop in this single run. It was about as fast as first building a million-item array, while using far less memory. Use generators where laziness, readability or memory matter, and plain loops for tight numeric inner loops. The JavaScript event loop guide explains how async generators interleave with other work.

When to use generators

  • Custom iterables and data structures.
  • Infinite or very large sequences, generated on demand.
  • Lazy multi-step pipelines over streams of data.
  • Tree and graph traversal with yield*.
  • Paged APIs and streams with async generators.
  • Avoid them for simple arrays where map or reduce is clearer.

Final thoughts

JavaScript generators give functions a pause button. With function*, yield and next() you can build lazy pipelines, endless sequences, clean iterators, tree walkers and async page streams in a few readable lines, with return() and finally for cleanup. They cost some raw speed, so keep them out of hot numeric loops, but for expressing sequences they are hard to beat. Python developers will recognise the same ideas from Python generators.

Frequently asked questions

What is a generator function in JavaScript?

It is a function declared with function and an asterisk. Calling it returns an iterator, and each call to next runs the body until the next yield, returning an object with value and done.

What does yield do in JavaScript?

yield pauses the generator and sends a value to the caller. When next is called again, the generator resumes right after the yield, and the argument passed to next becomes the result of the yield expression.

What is the difference between yield and return in a generator?

yield pauses and can be used many times. return ends the generator, sets done to true and supplies a final value that for of loops and spread syntax ignore.

Can a generator be reused?

No. A generator object is exhausted after one full pass. Call the generator function again for a fresh one, or implement Symbol.iterator so each loop gets a new generator.

What is an async generator?

It is a generator declared with async function and an asterisk that can use await inside. You consume it with for await of, which makes it ideal for paged API results and streams.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
Software Development

301 vs 302 Redirect: Differences, SEO Impact, 307 and 308

301 vs 302 redirect: the differences, SEO impact, 307 and 308, method changes, redirect chains and loops, all tested on…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Databases & SQL

SQL Random Rows: How to Select Random Rows Fast and Fairly

SQL random rows: how to select random rows fast and fairly, timing ORDER BY RANDOM, offsets and ID jumps, and…

Read article →
Databases & SQL

SQL Median: 4 Ways to Calculate the Median, With Tested Queries

SQL median explained: four tested ways to calculate the median, including percentile functions, window ranks, offsets and per group medians.

Read article →
Software Development

JavaScript Regex Explained: Patterns, Flags, Groups and Pitfalls

JavaScript regex explained: literals, flags, groups, named groups, lookarounds, matchAll, replace and the catastrophic backtracking trap, tested in Node.

Read article →
Software Development

Python property: Getters, Setters, Validation and cached_property

Python property explained: getters, setters, deleters, validation, read-only and computed attributes, and cached_property, with tested code.

Read article →
Software Development

Python Enum Explained: auto, IntEnum, StrEnum, Flag and Best Practices

Python enum explained with tested examples: Enum, auto, IntEnum, StrEnum, Flag, aliases, unique, JSON serialisation and match statements.

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
Software Development

401 vs 403: Unauthorized vs Forbidden, and When to Use Each

401 vs 403 explained: authentication vs authorization, the WWW-Authenticate header, when to return 404 instead, client reactions and a tested…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Databases & SQL

SQL ROUND Function: Decimals, Ties, CEIL, FLOOR and Money

SQL ROUND explained with tested queries: decimals, tie rules, the 2.675 float trap, negative digits, CEIL, FLOOR, truncation and rounding…

Read article →
Databases & SQL

Recursive CTE in SQL: Hierarchies, Paths, Series and Cycles

Recursive CTE in SQL explained with tested queries: org charts with levels and paths, walking up a tree, team sizes,…

Read article →
Software Development

JavaScript Deep Copy: structuredClone vs JSON vs Spread, Tested

JavaScript deep copy compared: spread, Object.assign, the JSON trick, structuredClone and a custom copy, tested on Dates, Maps, Sets, BigInt…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →
Databases & SQL

SQL UPDATE Statement: Safe Updates, UPDATE With JOIN and RETURNING

The SQL UPDATE statement explained with tested examples: WHERE guards, CASE updates, UPDATE with JOIN, the subquery NULL trap, RETURNING…

Read article →
Databases & SQL

SQL COUNT: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT) Explained

SQL COUNT explained: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT), NULLs and empty strings, conditional counts, HAVING, the LEFT JOIN trap and…

Read article →
Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →