Iterators & Generators — JavaScript interview guide
16 / 23Language EssentialsLow priorityMedium 15 min
Iterators & Generators
An iterator gives values one by one. A generator function (function*) can pause with yield and resume later.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
A generator pauses at yield and resumes on next()
Execution phaseStep 1/7
script.js
1function* ids() {2let id = 1;3while (true) {4yield id++;5}6}7▶const gen = ids();9console.log(gen.next().value);10console.log(gen.next().value);
Call Stack
last in, first outMemory / Scope
Global
| gen | Generator { ids } |
ids() — not started
no variables
Console
nothing printed yet
What happens:Calling ids() does NOT run its body. It just returns a generator object, paused before line 2.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Generators
Each call to next() runs until the next yield.
function* ids() {
let id = 1;
while (true) yield id++;
}
const gen = ids();
gen.next().value; // 1
gen.next().value; // 2Remember this
- for...of works on anything with Symbol.iterator.
- Generators are lazy: values are produced on demand.
Interview questions
What makes an object iterable?
It has a [Symbol.iterator]() method that returns an object with a next() method returning { value, done }.
Practice
- Make a range(start, end) object usable in for...of.