Lesson 20 — Generators
Functions that pause
A generator is written function* and can yield values one at a time. Calling it gives an iterator; each .next() runs the function until the next yield and returns { value, done }. Because it pauses, an endless while (true) loop is safe — it only runs as far as you ask.
function* abc() { yield "a"; yield "b"; }
const it = abc();
console.log(it.next().value); // a
console.log(it.next().value); // b
Why it matters: generators model streams, pagination and endless sequences without building huge arrays.
Use g.next().value to log the first 5 even numbers, one per line.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based JavaScript Intermediate courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for JavaScript Intermediate books — check the publication year so the examples match current versions.
Search Amazon →