Symbols, iterators, generators and Proxy · senior
Generators
A generator function (function*) returns an iterator that runs its body only on demand and pauses at each yield; next(value) resumes it and sends a value in, which makes generators good for lazy sequences, pausable flows and, in async form, streaming data.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Calling a generator function runs nothing; it returns a generator object that is both an iterator and an iterable.
- next(v) resumes the body; v becomes the result of the paused yield expression. The argument of the first next() is ignored because no yield is waiting yet.
- return(v) ends the generator (finally blocks still run); throw(err) throws at the paused yield.
- yield* delegates to another iterable or generator (useful for recursive tree walks).
- A return x inside the generator gives { value: x, done: true }; for...of and spread ignore that final value.
- Uses: lazy or infinite sequences, ID generators, tree traversal, redux-saga effects, splitting long work into steps.
- async/await is conceptually a generator plus a runner that resumes it when each promise settles.
The red pen
Common traps: mistake → fix
Mistake: The first next(5) sets x in const x = yield 1
Fix: the first next only starts the body; its argument is lost.
Mistake: for...of receives the generator's return value
Fix: it stops at done: true and ignores it.
Easy to hard
Questions interviewers ask, easy to hard
- What is a generator?
- Predict two-way communication with next(value).
- How do return() and throw() work? What happens to finally blocks?
- Walk a tree with yield*.
- Build a tiny run() that makes a generator behave like async/await.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.