Generators in JavaScript are special functions that can pause and resume execution.
They are useful when you want to produce values one at a time instead of all at once.

Generators are commonly used for:

  • Controlled iteration

  • Working with large data

  • Lazy evaluation

  • Custom data streams


What Are Generators in JavaScript?

A generator function:

  • Is defined using function*

  • Uses yield to return values

  • Returns an iterator object

  • Can pause its execution and continue later


Creating a Generator Function

JavaScript
1function* createSequence() {
2 yield 1;
3 yield 2;
4 yield 3;
5}
6
7let seq = createSequence();
8
9console.log(seq.next());
10console.log(seq.next());
11console.log(seq.next());
12console.log(seq.next());

Output:

JavaScript
1{ value: 1, done: false }
2{ value: 2, done: false }
3{ value: 3, done: false }
4{ value: undefined, done: true }

Explanation:

  • function* defines a generator

  • yield sends a value and pauses execution

  • next() resumes execution

  • When values end, done becomes true


Using Generators with for...of

JavaScript
1function* numbers() {
2 yield 10;
3 yield 20;
4 yield 30;
5}
6
7for (let num of numbers()) {
8 console.log(num);
9}

Explanation:

  • for...of works with generators

  • Each yield provides the next value

  • Loop stops automatically when done


Generator with Dynamic Logic

JavaScript
1function* range(start, end) {
2 while (start <= end) {
3 yield start;
4 start++;
5 }
6}
7
8for (let value of range(1, 3)) {
9 console.log(value);
10}

Explanation:

  • Generator controls the flow

  • Values are produced on demand

  • Useful for ranges, pagination, streams


Real-World Example: Paginated Data

JavaScript
1function* pages(totalPages) {
2 let page = 1;
3 while (page <= totalPages) {
4 yield "Page " + page;
5 page++;
6 }
7}
8
9for (let page of pages(3)) {
10 console.log(page);
11}

This pattern is useful for pagination and step-by-step workflows.


Why Generators Are Important

Understanding JavaScript generators helps you:

  • Build custom iterators

  • Process large data efficiently

  • Control execution flow

  • Improve performance with lazy evaluation

  • Write cleaner iteration logic


Quick Summary

  • function* creates a generator

  • yield returns values step by step

  • next() resumes execution

  • Generators return iterators

  • Works with for...of


Conclusion

Generators in JavaScript provide a powerful way to control iteration and execution flow.
They allow you to work with data lazily and efficiently, making them ideal for modern JavaScript applications.