Generators in Javascript - ES6 Feature
August 18th 2024 | 2 min read
117 | 7

Before getting into our blog, Do you know what Yield is?

Not this!!!
Even Javascript has an operator called Yield
Hello Everyone,
Welcome back to my blog π.
I hope you are all safe and that this blog finds you in good health οΈπ«Ά.
Introduction
Generators, an ES6 feature of Javascript, Functions that can be paused and resumed and Yield is used in Generators.
Some of the use cases that Generators provide:
π Generating Infinite and Normal Sequences
π Asynchronous Programming
π Creating Iterables
Usage of Generators
As always letβs understand Generators better with some real-time examples
I will illustrate the difference between a normal restaurant and the popular one, Javascript Restaurant.
Normal Restaurant
// Food served my Normal Restaurant
const orderDishList = [
"Veg Manchuria",
"Chicken Soup",
"Noodles",
"Garlic Nan",
"Chicken Biryani",
"Dessert"
]
const dishServed = (dish) => {
console.log(`served ${dish}`)
}
const serveTheOrder = function() {
for (const dish of orderDishList) {
dishServed(dish)
}
}
serveTheOrder();
/*Output*/
/*
"served Veg Manchuria"
"served Chicken Soup"
"served Noodles"
"served Garlic Nan"
"served Chicken Biryani"
"served Dessert"
*/
Please refresh the page if codepen is not loaded and please use browser console to see the results.
In a Normal Restaurant, Food is served all at once and By the time we started our last dish, it was cooled down and we didnβt enjoy the food.
Javascript Restaurant
// Food served my Javascript Restaurant
const orderDishList = [
"Veg Manchuria",
"Chicken Soup",
"Noodles",
"Garlic Nan",
"Chicken Biryani",
"Dessert"
];
const serveDish = function(dish) {
console.log(`served ${dish}`);
};
const serveTheOrder = function*() {
for (let dish of orderDishList) {
yield serveDish(dish);
}
};
const serve = serveTheOrder();
serve.next(); /* "served Veg Manchuria" */
serve.next(); /* "served Chicken Soup" */
serve.next(); /* "served Noodles" */
serve.next(); /* "served Garlic Nan" */
serve.next(); /* "served Chicken Biryani" */
serve.next(); /* "served Dessert" */
Please refresh the page if codepen is not loaded and please use browser console to see the results.
But, Javascript Restaurant served the food on demand so that we could enjoy the hot and delicious food.
Things to remember
β Do not use Generators inside the arrow function
β Do not use Yield inside forEach, Map, filter, etc. as there are callbacks.
β
Use for .. of and for-loop in Generators.
β
Use Normal functions for Generators.
Here we go, Thatβs it folks for this short blog.
I hope everyone liked this blog.
If you like it, give it a thumbs up π ,
and share it with your friend.
For more exciting content on Frontend, Please do follow me π―.
Thanks a lot, Everyone π.
Until Next time,
Happy Learning πβοΈ.
Abhishek Kovuri, UI developer