Understanding Generators in Javascript - Javascript weekly
Tags: showdev, webdev, tutorial, beginners
Published: 2019-06-30 11:00:36

---
title: Understanding Generators in Javascript - Javascript weekly
published: true
description: Understanding Generators in Javascript - Javascript weekly
tags: showdev,webdev,tutorial,beginners
series : javascript
canonical_url: https://cloudnweb.dev/2019/06/understanding-generators-in-javascript-javascript-weekly/
---

For regular updates, subscribe to weekly newsletter, <a href="http://eepurl.com/gvbr7j">Weekly Updates</a>.

<!-- wp:paragraph -->
<p>In this weekly series, we will see what is generators in javascript and use cases of generators. Understanding Generators in Javascript - Javascript weekly</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is Generators ?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Firstly , Let's try to understand this concept with a simple analogy.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> For example, Let's say that you are watching a movie on your laptop. suddenly someone at your doorbell, it is a pizza that you have ordered. you will pause the movie and get the pizza, come back and resume from the place where you left watching it. right?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Similarly ,<strong>Generators </strong>in javascript works in the same concept.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Generators </strong>are special functions in javascript which can be paused and resume from the place it left.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Moreover, we all know that once a normal javascript function gets executed, it is not possible to interrupt and do somework and comeback where it left off.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, Take a look at this code below</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>setTimeout(function(){
  console.log("Hello World");
},1);

function foo() {
  // NOTE: don't ever do crazy long-running loops like this
  for (var i=0; i&lt;=700; i++) {
      console.log(i);
  }
}

foo();</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p> However, setTimeout function will only execute after the loop ends. it is not possible to interrupt the for loop and execute the function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>  this is the problem that <strong>Generators </strong>functions solves.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":877} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/diag.png" alt="" class="wp-image-877"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Implementing Generators</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>  To define a function as a Generator function, we need to define it with a asterik(*) to it. For example,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function* getData() {
   //yield comes here.
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Every time a Generator function encounters an yield statement, it will execute it and resume the function after that.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's understand this concept with an example,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function* getData() {
  
  for(let i=0;i &lt; 10;i++){
    console.log(yield getUser(i));
  }

}

function getUser(value) {
    return {
      id : value,
      name : "John",
      age : 20 
    }
}

const get = getData();

console.log(get.next().value)
console.log(get.next().value)
console.log(get.next().value)
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Here, we define a generator function to fetch the user data. every time the getData() function encounters the yield statement with getUser() function, it executes the function and returns the data to the main function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> we need to call the<strong> next()</strong> to iterate and get the value from the generator function. it is called as<strong> Generator Iterator</strong>s.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>what is Generator Iterators ? </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>generator iterators are special kind of design patterns. we can loop through an ordered sets step by step. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, consider an array with values</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>['a','b','c','d','e']</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>with an iterator, we can loop through values one at a time using the keyword <strong>next()</strong>. the purpose of doing in this way is if we have some function to run after every value returned. we can execute in this way.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function *doIt() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>To step through the value of generator function <strong>doIt()</strong>. we need an iterator to be constructed. we can do that by defining,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>var it = doIt();</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p> Meanwhile, to iterate over the generator function, we need to use keyword <strong>next()</strong> to get the values.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>console.log( it.next() ); // { value:1, done:false }
console.log( it.next() ); // { value:2, done:false }</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>we get the value and something called <strong>done</strong> which indicates whether the iterator reached the end of the function or not.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>we can also use <strong>return</strong> instead of <strong>yield </strong>in the generator function. But, the problem with <strong>return </strong>is, in for..of loop return statement will be thrown away. it will not get executed</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>with for..of loop</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>function *doIt() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;
    return 6;
}

for (var v of doIt()) {
    console.log( v );
}
// 1 2 3 4 5

console.log( v ); // still `5`, not `6` :(</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Where do we use Generator functions ?</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4><a href="https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html">Redux-saga</a></h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p> Most importantly, redux saga is used to handle the side effects of redux. if you have worked with react/redux, you might know how difficult to maintain the action creators and reducers in redux.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Redux-saga eases the process of maintaining action-creators and reducers by grouping them called <strong>sagas</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Redux sagas explicitly uses Generators functions to do the saga effects such as</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Calling an API and get the data from the backend</li><li>selecting the value from the redux state</li><li>take every action and do some business logic and dispatch some other action.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4> Promise alternative</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p> Above all, it can also be used as a promise, async/await alternative.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Since,most of the developers used with promise, they won't use Generators that much.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But we can use Generator to solve the problem of what Promise,Async/Await solves.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Conclusion</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p> OK, so that's it for the basics of generators. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Likewise, we will see more about Javascript core concepts in the upcoming Javascript weekly series. Until then, you can read my other <a href="https://cloudnweb.dev/category/web-dev/">blog posts</a> which explain the fundamentals of web development.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Happy Coding</strong> :-)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Meanwhile ,To Read more about Javascript</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://github.com/getify/You-Dont-Know-JS">You Don't Know JS</a></p>
<!-- /wp:paragraph -->