Generators in Javascript - ES6 Feature

August 18th 2024 | 2 min read

117 |  7

Logo

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 🎯.

via GIPHY

Thanks a lot, Everyone πŸ™.
Until Next time,
Happy Learning πŸ“–βœοΈ.

Abhishek Kovuri, UI developer