Generator functions are functions that can be exited and later re-entered. Their context (variable bindings) is saved across re-entrances. They are declared using function* and return an iterator with yield.
JavaScript Generators
Pause and resume function execution on demand with function* and yield.
Key Takeaways: JavaScript Generators
Mastering JavaScript Generators helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
JavaScript Generators Code Example
JavaScriptfunction* idMaker() {
let index = 1;
while (index <= 3) {
yield index++;
}
}
const gen = idMaker();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
Output
1 2 3
Free sign-in required · Google login available
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services