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
yieldto return values -
Returns an iterator object
-
Can pause its execution and continue later
Creating a Generator Function
Output:
Explanation:
-
function*defines a generator -
yieldsends a value and pauses execution -
next()resumes execution -
When values end,
donebecomestrue
Using Generators with for...of
Explanation:
-
for...ofworks with generators -
Each
yieldprovides the next value -
Loop stops automatically when done
Generator with Dynamic Logic
Explanation:
-
Generator controls the flow
-
Values are produced on demand
-
Useful for ranges, pagination, streams
Real-World Example: Paginated Data
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 -
yieldreturns 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.