What is Generator in JavaScript: Explained with Examples
generator in JavaScript is a special type of function that can pause its execution and resume later, allowing it to produce multiple values over time. It uses the function* syntax and the yield keyword to return values one at a time.How It Works
Think of a generator like a bookmark in a book. When you read a normal function, it runs from start to finish without stopping. But a generator can pause at certain points, remember where it left off, and continue later when asked.
This is done using the yield keyword inside a function*. Each time the generator pauses, it gives back a value. When you ask it to continue, it picks up right after the last yield and runs until the next one or the end.
This makes generators great for handling sequences of values or tasks that happen over time, like reading lines from a file or generating numbers one by one.
Example
This example shows a generator that produces numbers from 1 to 3, one at a time.
function* countToThree() { yield 1; yield 2; yield 3; } const counter = countToThree(); console.log(counter.next().value); // 1 console.log(counter.next().value); // 2 console.log(counter.next().value); // 3 console.log(counter.next().done); // true
When to Use
Use generators when you want to produce a series of values over time without creating them all at once. This saves memory and lets you handle data step-by-step.
Common uses include:
- Generating sequences like numbers or dates.
- Reading large files or streams piece by piece.
- Implementing asynchronous workflows in a clear, stepwise manner.
Key Points
- Generators use
function*andyieldto pause and resume. - They return an iterator object with a
next()method. - Each
next()call resumes execution until the nextyield. - Generators help manage sequences and asynchronous flows efficiently.