JavaScript · The language round
What are generators and iterators in JavaScript?
Short answer
An iterator produces values one at a time through next(). A generator is a function that can pause at yield and resume later, making it easy to implement custom iterators and lazy sequences.
The iterator protocol is the contract behind for...of, spread and destructuring. An object is iterable if it has a Symbol.iterator method that returns an iterator with a next() method.
function* countTo(limit) {
for (let value = 1; value <= limit; value++) {
yield value;
}
}
const iterator = countTo(3);
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }Why generators are useful
- Lazy evaluation: values are produced only when requested
- Custom iteration over trees, paginated APIs or infinite sequences
- Cleaner state machines than manual index bookkeeping
yield*delegates to another iterable
function* ids() {
let id = 0;
while (true) {
yield id++;
}
}
const nextId = ids();
console.log(nextId.next().value); // 0
console.log(nextId.next().value); // 1Async generators combine async and function* and are consumed with for await...of. They are useful for streaming results from paginated APIs or server-sent events.
next() call.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the iterator protocol?
- 2How does `yield` pause execution?
- 3What is an async generator used for?
- 4How does `yield*` differ from `yield`?
Say it in the interview
An iterator exposes a next method that returns a value and a done flag. A generator is a function with an asterisk that can pause at yield and resume on the next call. Generators make custom iteration and lazy sequences much easier, including infinite sequences, because values are produced only when requested. Async generators do the same for asynchronous streams and are consumed with for await of.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.