In JavaScript, a generator is a special type of function that can pause its execution and later resume from the point where it left off. This is achieved using the function* syntax and the yield keyword. Generators return an iterator object, which allows you to manually control when the function executes by calling its .next() method.
Key Concepts:
1. function* Declaration: You declare a generator function using function* instead of just function.
2. yield Keyword: Inside a generator, the yield keyword pauses the function's execution and returns the value specified. When .next() is called on the iterator, the function resumes from the last yield.
Example:
function* myGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = myGenerator();
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 }
Explanation:
Each time you call gen.next(), the function resumes execution until it hits the next yield.
When the function finishes, done becomes true, and value is undefined.
Practical Use Cases:
Lazy Evaluation: Generators only compute values when requested, making them useful for managing large data sets.
Infinite Sequences: You can use generators to create infinite sequences, like iterating over numbers indefinitely.
Asynchronous Iteration: In combination with async and await, generators can be used to manage asynchronous code flow.
Get Haja Mydeen’s stories in your inbox
Join Medium for free to get updates from this writer.
Generators are powerful tools for writing more efficient and expressive code, especially when dealing with sequences, streams, or asynchronous tasks.
In real-time scenarios, JavaScript generators with yield are helpful for creating sequences of data without loading everything at once. Here's a breakdown of how this works in practice:
How yield and Generators Work in Real-Time:
1. Pause and Resume Execution: A generator allows a function to run up to a yield statement, pause there, and then resume later when needed. Think of it like stopping a movie at a certain point and pressing "play" when you're ready to continue.
2. Handling Large Data Sets: Instead of processing a large data set all at once, a generator can return one piece of data at a time, reducing memory usage. This is useful when dealing with large files or streams of data.
3. Iterating Asynchronously: In real-time scenarios, you might want to request data from a server or handle user inputs over time. Using a generator, you can request and process data chunk by chunk.
Real-Time Example:
Imagine a web app that loads user comments one by one as the user scrolls down:
function* loadComments() {
let commentId = 1;
while (true) {
yield fetch(`/comments/${commentId}`).then(response => response.json());
commentId++;
}
}
const commentsGenerator = loadComments();
// When the user scrolls down, load the next comment
document.addEventListener('scroll', async () => {
const nextComment = await commentsGenerator.next().value;
if (nextComment) {
displayComment(nextComment); // Function to add comment to the page
}
});
How It Works in Real Time:
Lazy Loading: Each time the user scrolls, the generator fetches the next comment, so only one comment is loaded at a time instead of fetching all comments at once.
Efficient Memory Usage: Instead of holding all comments in memory, it fetches them on demand.
Async Handling: The yield keyword returns a Promise from the fetch() call. The next comment is fetched only when the user scrolls.
This approach helps in managing real-time data like loading new items in an infinite scroll, processing data streams, or handling large datasets efficiently, without overwhelming the system.







