JavaScript Generators
Generators are special functions in JavaScript that can be paused and resumed, making them useful for handling asynchronous tasks, infinite sequences, and memory-efficient iteration.
🔹 1. What is a Generator?
A generator function is defined using function*
(with an asterisk *
after function
) and uses the yield
keyword to pause execution.
🔹 Basic Syntax
✔ Each yield
pauses execution and returns a value.
✔ Calling next()
resumes execution from the last yield
.
✔ When return
is reached, done: true
indicates completion.
🔹 2. Iterating Over a Generator
Generators are iterable, meaning you can use them in a for...of
loop.
✔ Looping stops automatically when done: true
.
🔹 3. Infinite Generators
Since generators pause execution, they are great for infinite sequences without blocking memory.
✔ Unlike an infinite loop, this does not block execution.
🔹 4. Generator with Arguments
You can pass arguments to next()
to send values back into the generator.
✔ The value passed to next(value)
is received inside the generator as yield
's result.
🔹 5. Delegating Generators (yield*
)
A generator can delegate to another generator using yield*
.
✔ yield*
includes all values from another generator.
🔹 6. Error Handling in Generators
Errors can be thrown inside a generator using throw()
.
✔ Errors can be handled inside the generator.
🔹 7. Async Generators (async function*
)
An async generator
allows await
inside and produces asynchronous values.
✔ Useful for streaming data asynchronously.
🔹 8. Summary
✔ Generators (function*
) allow pausing/resuming execution.
✔ Use yield
to pause, and next()
to resume.
✔ They are memory-efficient and great for infinite sequences.
✔ Use yield*
to delegate to another generator.
✔ Use throw()
inside a generator to handle errors.
✔ async function*
allows working with async data streams.
🚀 Generators provide powerful control over execution flow!