mediumFrontend EngineerTechnology
How do JavaScript iterators and generators work with for...of and spread syntax?
Posted 18/04/2026
by Mehedy Hasan Ador
Question Details
At a tech interview: "Implement a custom iterable that generates a range of numbers and explain the iterator protocol."
Suggested Solution
Iterator Protocol
const range = {
from: 1, to: 5,
[Symbol.iterator]() {
return { current: this.from, last: this.to,
next() { return this.current <= this.last ? { value: this.current++, done: false } : { done: true }; }
};
}
};
for (const num of range) console.log(num); // 1,2,3,4,5
[...range]; // [1,2,3,4,5]
Async Iterator for Paginated API
async function* fetchPages(url) {
let page = 1;
while (true) {
const data = await fetch(${url}?page=${page++}).then(r => r.json());
if (!data.length) return;
yield data;
}
}
for await (const page of fetchPages("/api/apps")) render(page);
Built-in iterables: String, Array, Map, Set, NodeList — all implement Symbol.iterator.