5 min read
•Question 30 of 50hardWhat are Iterators and Generators?
Understanding iteration protocols in JavaScript.
What You'll Learn
- Iterator protocol
- Generator functions
- Practical use cases
Iterator Protocol
An object is iterable if it has a [Symbol.iterator] method.
code.jsJavaScript
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
if (current <= last) {
return { value: current++, done: false };
}
return { done: true };
}
};
}
};
for (const num of range) {
console.log(num); // 1, 2, 3, 4, 5
}Generator Functions
Use function* to create generators.
code.jsJavaScript
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGenerator();
gen.next(); // { value: 1, done: false }
gen.next(); // { value: 2, done: false }
gen.next(); // { value: 3, done: false }
gen.next(); // { value: undefined, done: true }
// Spread into array
[...numberGenerator()]; // [1, 2, 3]Practical Examples
code.jsJavaScript
// Infinite sequence
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
// Take first 10
const fib = fibonacci();
const first10 = Array.from({ length: 10 }, () => fib.next().value);
// Async generator
async function* fetchPages(urls) {
for (const url of urls) {
const response = await fetch(url);
yield await response.json();
}
}
for await (const page of fetchPages(urls)) {
console.log(page);
}