JavaScript Generator Functions
What is a Generator Function?
A generator function is a special type of function in JavaScript that can be paused and resumed. It allows you to create iterators, which can produce a sequence of values over time, instead of computing them all at once.
Syntax
A generator function is defined using the function* syntax:
function* generatorFunction() {
// function body
}Features of generator functions:
- Yield Keyword: Inside a generator function, you use the
yieldkeyword to produce a value and pause the function's execution. - Iterator: When you call a generator function, it returns an iterator. You can use this iterator to control the execution of the generator function.
- State Preservation: Each time the generator function is called, it resumes execution from where it last a value, preserving its state.
Examples of generator function
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }Get Neetish Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
Explanation of above example
- Calling the Generator: When you call
numberGenerator(), it does not execute the function. Instead, it returns an iterator. - Using
next(): Callinggen.next()executes the generator until the nextyield, returning an object with two properties: - value: The yielded value.
- done: A boolean indicating if the generator has finished executing.
Using yield*
- we can delegate to another generator function using yield*:
function* innerGenerator() {
yield 'inner 1';
yield 'inner 2'
}
function* outerGenerator() {
yield 'outer 1';
yield* innerGenerator();
yield 'outer 2';
}
const gen = outerGenerator();
console.log(gen.next()); // { value: 'outer 1', done: false }
console.log(gen.next()); // { value: 'inner 1', done: false }
console.log(gen.next()); // { value: 'inner 2', done: false }
console.log(gen.next()); // { value: 'outer 2', done: false }
console.log(gen.next()); // { value: undefined, done: true }Sending Values to Generators
we can send values back into a generator using the next()method. The value you pass in will become the result of the yield expression.
function* echoGenerator() {
const message1 = yield `what you want to say?`
console.log(`you said ${message1}`)
}
const echo = echoGenerator();
console.log(echo.next()); //{ value: 'what you want to say?', done: false }
console.log(echo.next("hello"))
// you said hello { value: undefined, done: true }Practical Use Cases:
- Asynchronous Programming: Generators can help manage asynchronous operations. They allow you to write code that looks synchronous, using yield to pause execution while waiting for promises.
- Custom Iterators: You can create complex data structures with custom iteration logic, such as trees or graphs.
- Infinite Sequences: Generators can produce infinite sequences without consuming memory for all values at once.
Conclusion
- Generator functions are a powerful feature in JavaScript, allowing you to create iterators with state and control their execution flow.
- By leveraging the yield keyword, you can manage sequences of values, handle asynchronous programming elegantly, and create custom data structures.





