BeginnerCoder

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.

Want it another way?
Task

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.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with JavaScript Intermediate

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.