Iterators and generators
The iterator protocol
An iterator is an object with a next method that returns a value plus a done flag. Loops call next until done becomes true, so any object with that shape can drive a loop.
Iterables add a computed method keyed by Symbol.iterator that creates a fresh iterator. Arrays, maps, sets, and strings already follow this contract out of the box. The program takes two steps of one array iterator and prints each result.
const nums = [10, 20, 30]; const it = nums[Symbol.iterator](); console.log(it.next()); console.log(it.next());
{ value: 10, done: false }
{ value: 20, done: false }
function* generators
Writing next by hand gets tedious, so generator functions build iterators for you. A function star returns a paused sequence that resumes on each next call.
Use generators when the sequence has logic: counters, ranges, retries, or paged reads. The function body reads top to bottom while callers consume values one by one. The program counts to three and prints every value.
function* countUp(limit: number): Generator<number> { for (let i = 1; i <= limit; i++) { yield i; } } for (const n of countUp(3)) { console.log(n); }
1
2
3
Yield values
Yield pauses the generator and hands one value to the caller. On the next request the function resumes right after that yield with all locals intact.
Yield delegation with yield star forwards to another generator. It keeps each sequence short while still exposing one flat stream to the loop. The program walks the trip and prints its three places.
function* pair(): Generator<string> { yield "north"; yield "south"; } function* trip(): Generator<string> { yield* pair(); yield "home"; } for (const place of trip()) { console.log(place); }
north
south
home
Lazy pipelines
Generators shine in pipelines because each stage pulls only what it needs. Map and take helpers stay lazy, so a huge range never materializes in memory at once.
Build the pipeline from small generators, then consume with a plain for loop. The code reads as data flow while the runtime does minimal work per step. The program takes two values from a range and prints them doubled.
function* numbers(): Generator<number> { yield 1; yield 2; yield 3; } function* take(source: Generator<number>, n: number): Generator<number> { let seen = 0; for (const v of source) { if (seen >= n) break; seen++; yield v * 2; } } for (const v of take(numbers(), 2)) { console.log(v); }
2
4
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What shape does an iterator have?
Answer
A
nextmethod that returns a value and a done flagThe loop calls
nextuntildoneis true, and any object of that shape can drive it. -
What does a generator function return when it is called?
Answer
An iterator whose body runs step by step
The call pauses at once and the body resumes only when
nextis called. -
What does
yield*do?Answer
It forwards to another iterator and yields each of its values
Delegation keeps one flat stream for the caller while each sequence stays short.
-
Why is a generator pipeline lazy?
Answer
Each stage pulls only the values the next one asks for
A huge range never materializes at once, because work happens per requested value.
-
What does this program print?
const nums = [10, 20]; const it = nums[Symbol.iterator](); console.log(it.next()); console.log(it.next()); console.log(it.next());Answer
{ value: 10, done: false } / { value: 20, done: false } / { value: undefined, done: true }
The third call is past the last value, so it reports done with no value.
-
What does this program print?
function* countUp(limit: number): Generator<number> { for (let i = 1; i <= limit; i++) { yield i; } } for (const n of countUp(2)) { console.log(n * 10); }Answer
10 / 20
The loop consumes 1 and 2, and each value is multiplied before it is printed.
-
What does this program print?
function* pair(): Generator<string> { yield "north"; yield "south"; } function* trip(): Generator<string> { yield* pair(); yield "home"; } for (const place of trip()) { console.log(place); }Answer
north / south / home
The delegated pair comes first, and home follows after it ends.
-
What does this program print?
function* numbers(): Generator<number> { yield 1; yield 2; yield 3; } let total = 0; for (const n of numbers()) { total += n; } console.log(total);Answer
6
The loop adds 1, 2 and 3, and the sum is printed once.
-
What does the compiler say about this program?
function* countUp(): Generator<number> { yield "one"; } console.log(countUp);Answer
error TS2322: Type 'string' is not assignable to type 'number'.
The generator promises numbers, and the yielded string does not fit.
-
What does the compiler say about this program?
const it = [1, 2][Symbol.iterator](); const n: string = it.next().value; console.log(n);Answer
error TS2322: Type 'number | undefined' is not assignable to type 'string'.
The array holds numbers, and the value of the iterator result carries that type.
Article author: Arthur Isaev