JavaScript Iterators and Generators: Symbol.iterator, yield and Async Generators

Why does for...of work on arrays, strings, Maps and Sets, but not on plain objects? The answer is the iteration protocol, and once you understand it you can make your own objects loopable. Generators, functions written with function* and yield, are the easy way to create iterators: they produce values one at a time, on demand. In this lesson you will learn both, then use them for lazy sequences, unique test data and paginated API results with async generators.

Advertisement

πŸ“– What You’ll Learn: what iterables and iterators are, the iteration protocol and next(), Symbol.iterator, making a custom object iterable, generator functions with function* and yield, generator objects and their states, lazy and infinite sequences, yield*, passing values into generators, iterator helpers (map, filter, take, toArray), async generators and for await…of, and practical test-data and pagination examples.


πŸ” Iterables and Iterators

Definitions: an iterable is any object that can be looped over with for...of, spread (...) or destructuring. An iterator is the object that actually produces the values, one at a time, through a next() method. Each call to next() returns { value, done }.

πŸ“„ protocol.js

const browsers = ["chromium", "firefox"];
const it = browsers[Symbol.iterator]();   // ask the array for an iterator

console.log(it.next());
console.log(it.next());
console.log(it.next());                   // finished

// for...of does exactly this behind the scenes
for (const b of browsers) console.log("for...of:", b);

⌨️ Terminal

node protocol.js

πŸ–₯️ Output

{ value: 'chromium', done: false }
{ value: 'firefox', done: false }
{ value: undefined, done: true }
for...of: chromium
for...of: firefox
Built-in iterablesWhat you get
ArrayEach element
StringEach character (by code point)
Map[key, value] pairs
SetEach value
arguments, NodeList, matchAll results, entries()/keys()/values()Their items
Plain objectNot iterable (use Object.entries)

πŸ“„ not-iterable.js

try {
  for (const x of { a: 1 }) console.log(x);
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node not-iterable.js

πŸ–₯️ Output

TypeError: {(intermediate value)} is not iterable

πŸ”‘ Making an Object Iterable with Symbol.iterator

To make your own object work with for...of, give it a method under the special key Symbol.iterator that returns an iterator:

πŸ“„ custom-iterable.js

const testRange = {
  from: 1,
  to: 4,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next() {
        return current <= last
          ? { value: `test-${current++}`, done: false }
          : { value: undefined, done: true };
      },
    };
  },
};

for (const id of testRange) console.log(id);
console.log([...testRange]);
const [first, second] = testRange;
console.log(first, second);

⌨️ Terminal

node custom-iterable.js

πŸ–₯️ Output

test-1
test-2
test-3
test-4
[ 'test-1', 'test-2', 'test-3', 'test-4' ]
test-1 test-2

Writing next() by hand is verbose and easy to get wrong. Generators do the same job with far less code.


Advertisement

βš™οΈ Generator Functions: function* and yield

Definition: a generator function, written function*, can pause in the middle and resume later. Each yield value hands one value to the caller and pauses. Calling a generator function does not run its body; it returns a generator object, which is both an iterator and an iterable.

πŸ“„ generator.js

function* steps() {
  console.log("  (starting)");
  yield "open page";
  console.log("  (resumed after step 1)");
  yield "log in";
  yield "check dashboard";
  return "done";              // the return value is not part of for...of
}

const gen = steps();          // nothing printed yet: the body has not started
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());      // finished generators keep returning done: true

console.log([...steps()]);    // a fresh generator, collected into an array

⌨️ Terminal

node generator.js

πŸ–₯️ Output

  (starting)
{ value: 'open page', done: false }
  (resumed after step 1)
{ value: 'log in', done: false }
{ value: 'check dashboard', done: false }
{ value: 'done', done: true }
{ value: undefined, done: true }
  (starting)
  (resumed after step 1)
[ 'open page', 'log in', 'check dashboard' ]
  • The body runs only when next() is called, and only up to the next yield.
  • Local variables keep their values between pauses.
  • The return value appears once with done: true; for...of and spread ignore it.
  • A generator object can be iterated only once. Call the function again for a new sequence.

The custom iterable from the previous section, rewritten as a generator:

πŸ“„ generator-iterable.js

const testRange = {
  from: 1,
  to: 4,
  *[Symbol.iterator]() {          // generator method
    for (let i = this.from; i <= this.to; i++) yield `test-${i}`;
  },
};
console.log([...testRange]);

⌨️ Terminal

node generator-iterable.js

πŸ–₯️ Output

[ 'test-1', 'test-2', 'test-3', 'test-4' ]

♾️ Lazy and Infinite Sequences

Because generators produce values only when asked, they can describe sequences that would be too large, or even infinite, to build as an array. You take only what you need:

πŸ“„ infinite.js

function* idGenerator(prefix = "user") {
  let n = 1;
  while (true) {                     // infinite, but lazy
    yield `${prefix}-${String(n++).padStart(4, "0")}`;
  }
}

const ids = idGenerator();
console.log(ids.next().value, ids.next().value, ids.next().value);

function* take(iterable, count) {
  for (const item of iterable) {
    if (count-- <= 0) return;
    yield item;
  }
}
console.log([...take(idGenerator("order"), 3)]);

⌨️ Terminal

node infinite.js

πŸ–₯️ Output

user-0001 user-0002 user-0003
[ 'order-0001', 'order-0002', 'order-0003' ]

⚠️ Watch out: Never spread or Array.from an infinite generator directly ([...idGenerator()]): it never ends and the program hangs or runs out of memory. Always limit it with take, a break, or the iterator helpers below.


🧰 Iterator Helpers: map, filter, take, toArray

ES2025 added iterator helpers: array-like methods directly on iterators, which stay lazy. They work on generators and on built-in iterators such as map.values() (Node.js 22+):

πŸ“„ helpers.js

function* naturals() {
  let n = 1;
  while (true) yield n++;
}

const firstEvenSquares = naturals()
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .take(5)
  .toArray();
console.log(firstEvenSquares);

const scores = new Map([["asha", 91], ["ravi", 58], ["meera", 85]]);
console.log(scores.values().filter((s) => s >= 60).toArray());
console.log(naturals().drop(10).take(3).toArray());
console.log(naturals().some((n) => n > 100), naturals().find((n) => n % 7 === 0));

⌨️ Terminal

node helpers.js

πŸ–₯️ Output

[ 4, 16, 36, 64, 100 ]
[ 91, 85 ]
[ 11, 12, 13 ]
true 7

Only five numbers were squared even though naturals() is infinite, because each helper pulls one value at a time.


Advertisement

πŸ”— yield* and Passing Values In

yield* delegates to another iterable, yielding all of its values:

πŸ“„ delegate.js

function* smokeSuite() {
  yield "login";
  yield "search";
}
function* regressionSuite() {
  yield* smokeSuite();          // include every smoke test
  yield* ["refund", "export"];  // any iterable works
  yield "audit log";
}
console.log([...regressionSuite()]);

⌨️ Terminal

node delegate.js

πŸ–₯️ Output

[ 'login', 'search', 'refund', 'export', 'audit log' ]

next(value) sends a value into the generator: it becomes the result of the paused yield expression. This two-way communication is what early async libraries used before async/await existed:

πŸ“„ two-way.js

function* conversation() {
  const name = yield "What is your name?";
  const role = yield `Hi ${name}, what is your role?`;
  return `${name} is a ${role}`;
}

const chat = conversation();
console.log(chat.next().value);          // first next() starts the generator
console.log(chat.next("Asha").value);
console.log(chat.next("tester").value);

⌨️ Terminal

node two-way.js

πŸ–₯️ Output

What is your name?
Hi Asha, what is your role?
Asha is a tester

⏳ Async Generators and for await…of

Definition: an async generator (async function*) can await inside its body and yields values asynchronously. You consume it with for await...of. This is ideal for data that arrives in pieces, such as paginated API results or lines of a large file.

πŸ“„ async-generator.js

// Simulated API: 7 orders, 3 per page
const ALL = Array.from({ length: 7 }, (_, i) => ({ id: 100 + i }));
const fakeFetchPage = (page) =>
  new Promise((resolve) => setTimeout(() => {
    const items = ALL.slice((page - 1) * 3, page * 3);
    resolve({ items, hasMore: page * 3 < ALL.length });
  }, 5));

async function* allOrders() {
  let page = 1;
  while (true) {
    const { items, hasMore } = await fakeFetchPage(page);
    console.log(`  fetched page ${page} (${items.length} items)`);
    yield* items;
    if (!hasMore) return;
    page++;
  }
}

async function main() {
  const ids = [];
  for await (const order of allOrders()) {
    ids.push(order.id);
    if (ids.length === 5) break;      // stop early: page 3 is never fetched
  }
  console.log(ids);
}
main();

⌨️ Terminal

node async-generator.js

πŸ–₯️ Output

  fetched page 1 (3 items)
  fetched page 2 (3 items)
[ 100, 101, 102, 103, 104 ]

The caller loops over orders as if they were one list, while the generator fetches pages only when needed. Breaking out after five items means the third page is never requested. Promises and async/await are explained fully in Module 10.


πŸ§ͺ Tester Scenario: A Test-Data Factory

Generators make test-data factories that never run out and never repeat. This one produces unique users, cycles through roles, and can be limited with iterator helpers:

πŸ“„ factory.js

function* cycle(values) {
  while (true) yield* values;
}

function* userFactory(runId) {
  const roles = cycle(["tester", "admin", "viewer"]);
  let n = 1;
  while (true) {
    yield {
      username: `${runId}_user${n}`,
      email: `qa+${runId}-${n}@sqatools.in`,
      role: roles.next().value,
    };
    n++;
  }
}

const users = userFactory("run42");
const firstThree = users.take(3).toArray();
console.table(firstThree);

const admins = userFactory("run43").filter((u) => u.role === "admin").take(2).toArray();
console.log(admins.map((u) => u.username));

⌨️ Terminal

node factory.js

πŸ–₯️ Output

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ (index) β”‚ username      β”‚ email                    β”‚ role     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 0       β”‚ 'run42_user1' β”‚ 'qa+run42-1@sqatools.in' β”‚ 'tester' β”‚
β”‚ 1       β”‚ 'run42_user2' β”‚ 'qa+run42-2@sqatools.in' β”‚ 'admin'  β”‚
β”‚ 2       β”‚ 'run42_user3' β”‚ 'qa+run42-3@sqatools.in' β”‚ 'viewer' β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
[ 'run43_user2', 'run43_user5' ]
  • cycle repeats a list forever, here giving a predictable rotation of roles.
  • Every user is unique within a run because the counter only goes up, and the run ID separates different runs.
  • Nothing is created until it is needed, so the factory costs nothing until a test asks for a user.

Advertisement

πŸ“ Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Use an array’s iterator directly: call next() on ["a", "b"][Symbol.iterator]() three times and print each result.

Show answer

πŸ“„ practice1.js

const it = ["a", "b"][Symbol.iterator]();
console.log(it.next(), it.next(), it.next());

πŸ–₯️ Output

{ value: 'a', done: false } { value: 'b', done: false } { value: undefined, done: true }

Q2. Write a generator countdown(n) that yields n, n-1, … 1 and then "Liftoff". Print all values with spread.

Show answer

πŸ“„ practice2.js

function* countdown(n) {
  for (let i = n; i >= 1; i--) yield i;
  yield "Liftoff";
}
console.log([...countdown(5)]);

πŸ–₯️ Output

[ 5, 4, 3, 2, 1, 'Liftoff' ]

Q3. Write an infinite generator of Fibonacci numbers and print the first 10 using take and toArray.

Show answer

πŸ“„ practice3.js

function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}
console.log(fibonacci().take(10).toArray());

πŸ–₯️ Output

[
  0, 1,  1,  2,  3,
  5, 8, 13, 21, 34
]

Q4. Make a playlist object with a songs array that is iterable and yields "1. Song name" strings.

Show answer

πŸ“„ practice4.js

const playlist = {
  songs: ["Intro", "Main Theme", "Outro"],
  *[Symbol.iterator]() {
    for (const [i, s] of this.songs.entries()) yield `${i + 1}. ${s}`;
  },
};
for (const line of playlist) console.log(line);

πŸ–₯️ Output

1. Intro
2. Main Theme
3. Outro

Q5. Write a generator chunks(array, size) that yields the array in groups of size. Test with [1..7] and size 3.

Show answer

πŸ“„ practice5.js

function* chunks(array, size) {
  for (let i = 0; i < array.length; i += size) {
    yield array.slice(i, i + size);
  }
}
console.log([...chunks([1, 2, 3, 4, 5, 6, 7], 3)]);

πŸ–₯️ Output

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]

Chunking is useful for sending test data to an API in batches.

Q6. Use iterator helpers to get the first 3 multiples of 7 that are greater than 50, from an infinite generator of natural numbers.

Show answer

πŸ“„ practice6.js

function* naturals() {
  let n = 1;
  while (true) yield n++;
}
console.log(naturals().filter((n) => n > 50 && n % 7 === 0).take(3).toArray());

πŸ–₯️ Output

[ 56, 63, 70 ]

🧠 MCQ Quiz: Iterators and Generators

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does an iterator’s next() method return?
  2. Which of these is NOT iterable with for…of?
  3. What makes an object iterable?
  4. What happens when you call a generator function?
  5. What does yield do?
  6. What does [...gen()] do with a generator’s return value?
  7. What is the danger of [...infiniteGenerator()]?
  8. What does yield* other do?
  9. How do you consume an async generator?
  10. What does naturals().take(3).toArray() return if naturals yields 1, 2, 3, …?

πŸ’Ό Interview Questions and Answers

Q1. What is the difference between an iterable and an iterator?

An iterable is an object with a [Symbol.iterator]() method; calling that method returns an iterator. An iterator is an object with a next() method that returns { value, done }. for...of, spread and destructuring ask the iterable for a fresh iterator and call next() until done is true. Generator objects are both: their [Symbol.iterator]() returns themselves.

Q2. What are generators useful for in real projects?

  • Lazy sequences: generating data on demand instead of building large arrays.
  • Infinite streams: unique IDs, test data, retry delays.
  • Custom iteration for data structures (trees, paginated results).
  • Async generators for streaming APIs, pagination and reading large files line by line.
  • Historically, coroutine-style async code (libraries such as co and redux-saga).

Q3. Predict the output.

πŸ“„ predict.js

function* g() {
  const x = yield 1;
  console.log("received", x);
  yield x * 2;
}
const it = g();
console.log(it.next(5).value);
console.log(it.next(10).value);
console.log(it.next().done);

⌨️ Terminal

node predict.js

πŸ–₯️ Output

1
received 10
20
true

The first next(5) starts the generator; the 5 is discarded because no yield is waiting yet, and it yields 1. next(10) resumes with x = 10, logs “received 10” and yields 20. The last call finishes the generator, so done is true.

Q4. How would you iterate over all items of a paginated API in a test?

Write an async generator that requests page after page, yields the items of each page, and stops when the API reports no more pages. The test then uses for await (const item of allItems()), can stop early with break, and never needs to know about pages. Add a page limit as a safety net so a buggy API cannot cause an endless loop.


Advertisement

❓ Frequently Asked Questions

πŸ€” Are generators slow?

They have a small overhead per value compared with a plain loop. For test data and I/O-bound work this is irrelevant; the benefit is clear, lazy code.

πŸ€” Can arrow functions be generators?

No. There is no arrow syntax for generators; use function* or a generator method *name() {}.

πŸ€” What is the difference between return and yield in a generator?

yield produces a value and pauses; the generator can continue. return ends the generator; its value appears once with done: true and is ignored by for...of.

πŸ€” Do iterator helpers work in browsers?

They are part of ES2025 and supported in current Chrome, Edge, Firefox and Safari, and in Node.js 22 and later.


🏁 Summary

  • Iterables have [Symbol.iterator](); iterators have next() returning { value, done }; for...of uses both.
  • Plain objects are not iterable; make your own objects iterable with a Symbol.iterator method.
  • Generators (function*) pause at each yield, which makes custom iterators and lazy or infinite sequences easy.
  • Iterator helpers (map, filter, take, toArray) work lazily on any iterator.
  • Async generators with for await...of stream data such as paginated API results.

Next, continue with Lesson 38: Prototypes. This completes Module 7. Module 8 covers object-oriented JavaScript: prototypes, classes and inheritance.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in