Predict Generator Output
Predict Output Medium
Question
What does this code print?
Code
function* counter() {
yield 1;
yield 2;
yield 3;
}
const gen = counter();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
Hint
Generators produce values one at a time via next().
Explanation
Generator functions (declared with function*) produce values lazily via yield. Each call to gen.next() resumes execution until the next yield and returns { value, done }. The first next() yields 1, the second yields 2, the third yields 3. Each .value is printed on its own line.
Related Resources
Related Lessons
- JavaScript Functions
Learn about generators.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.