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.
π 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 iterables | What you get |
|---|---|
| Array | Each element |
| String | Each character (by code point) |
| Map | [key, value] pairs |
| Set | Each value |
arguments, NodeList, matchAll results, entries()/keys()/values() | Their items |
| Plain object | Not 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.
βοΈ 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 nextyield. - Local variables keep their values between pauses.
- The
returnvalue appears once withdone: true;for...ofand 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.
π 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' ]
cyclerepeats 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.
π 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. OutroQ5. 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.
- What does an iterator’s
next()method return?Answer: An object { value, done }. done is true when the sequence is finished. - Which of these is NOT iterable with for…of?Answer: A plain object {}. Use Object.entries(obj) to iterate objects.
- What makes an object iterable?Answer: A method under the key Symbol.iterator that returns an iterator. This is the iteration protocol.
- What happens when you call a generator function?Answer: It returns a generator object without running the body. The body starts on the first next() call.
- What does
yielddo?Answer: Produces a value and pauses the generator. Execution resumes at the next next() call. - What does
[...gen()]do with a generator’s return value?Answer: Ignores it. Only yielded values are collected. - What is the danger of
[...infiniteGenerator()]?Answer: It never finishes. Limit infinite generators with take or break. - What does
yield* otherdo?Answer: Yields every value from another iterable. It delegates to another generator or any iterable. - How do you consume an async generator?Answer: for await…of. Each iteration awaits the next yielded value.
- What does
naturals().take(3).toArray()return if naturals yields 1, 2, 3, β¦?Answer: [1, 2, 3]. Iterator helpers are lazy and stop after three values.
πΌ 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.
β 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 havenext()returning{ value, done };for...ofuses both. - Plain objects are not iterable; make your own objects iterable with a
Symbol.iteratormethod. - Generators (
function*) pause at eachyield, 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...ofstream 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