Generator functions and yield
Quick answer
A generator function creates a suspended generator object. Calling next advances execution to a yield or completion.
How it works
Use function* name(){ yield value; }. Calling name does not execute the body immediately. Each next call resumes the current execution context; yield returns a value with done false and pauses. A return value appears with done true. Separate generator calls create separate state. Generator objects implement the iterable protocol and are commonly consumed once.
function* g(){console.log("body");yield 4;return 9;} const it=g();console.log("created");console.log(it.next().value);console.log(it.next().done);Expected output in Node.js:
createdbody4trueThe body starts on the first next.
function* g(){yield 2;yield 3;return 99;} console.log(JSON.stringify([...g()]));Expected output in Node.js:
[2,3]Spread omits the final return value.
Common mistakes
Do not confuse a generator function with its returned generator object. for...of does not include the final return value.
Practice
Write a generator yielding squares for a bounded range. Inspect its final next result manually.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generator functions and yield — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
When does a newly called generator function begin executing its body?
What is done after an ordinary yield?
Does each call to a generator function create a fresh generator?
What is the exact console output in Generator functions and yield example 1?
function* g(){console.log("body");yield 4;return 9;} const it=g();console.log("created");console.log(it.next().value);console.log(it.next().done);What is the exact console output in Generator functions and yield example 2?
function* g(){yield 2;yield 3;return 99;} console.log(JSON.stringify([...g()]));