Question presented to candidate: "A generator function looks like it 'returns' multiple times via yield. What actually happens when you call one — does its body run immediately, and can you pass a value BACK INTO it while it's paused?"
What a strong answer should cover:
- 📌 Interview term:
function*— declares a generator function; calling it does not run its body — it returns a genuine generator object (both an iterator and an iterable, covered in this bank's own dedicated iterator/iterable question) that controls execution via.next(). - 📌 Interview term: the real, direct answer to the prompt's laziness question — verified directly: calling a generator function genuinely does not execute any of its body — a
console.logas the very first line inside the body genuinely did not print until the FIRST.next()call, confirmed by the exact real ordering of output. - 📌 Interview term: pause and resume — each
yieldgenuinely pauses execution, returning{ value, done: false }; the next.next()call genuinely resumes exactly where it left off, up to the nextyieldor areturn/end of the function. - 📌 Interview term: the real, direct answer to the prompt's two-way question — verified directly: a value passed as
.next(value)'s own argument genuinely becomes the evaluated result of theyieldexpression the generator is currently paused on — confirmed directly via realconsole.loglines printed from INSIDE the generator body between calls, showing the exact value received. - A precise answer names that a generator object genuinely has its own
Symbol.iterator(verified directly), making it directly usable withfor...of/spread — thoughfor...ofonly reads yielded VALUES and does not support sending values back in via.next(value).
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering both the laziness and the two-way-communication parts of the prompt with real proof is the strong signal.
Code / implementation expected: Yes — a real generator driven through multiple explicit .next() calls, with console.log lines printed from inside its own body, is the clearest, most convincing demonstration of both laziness and two-way communication.