<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Abdulmuqsit Adam</title>
    <description>The latest articles on DEV Community by Abdulmuqsit Adam (@muqsitadam).</description>
    <link>https://dev.to/muqsitadam</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F963176%2F777588f2-af70-4e8d-af36-18307368e401.jpeg</url>
      <title>DEV Community: Abdulmuqsit Adam</title>
      <link>https://dev.to/muqsitadam</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/muqsitadam"/>
    <language>en</language>
    <item>
      <title>Javascript Generators: A Beginner's Guide</title>
      <dc:creator>Abdulmuqsit Adam</dc:creator>
      <pubDate>Thu, 03 Nov 2022 23:59:17 +0000</pubDate>
      <link>https://dev.to/muqsitadam/javascript-generators-a-beginners-guide-1ojf</link>
      <guid>https://dev.to/muqsitadam/javascript-generators-a-beginners-guide-1ojf</guid>
      <description>&lt;p&gt;Recently, I’ve had to pick up some JavaScript concepts to better reaffirm my understanding before moving on to work with them in React, and Generators was one of those concepts I had some little unrest understanding. I decided to piece together the basics to serve as a beginner’s working guide to generators.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction: What are Generators?
&lt;/h2&gt;

&lt;p&gt;According to the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*" rel="noopener noreferrer"&gt;MDN resource&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Generator functions are similar to regular functions, except that they can be paused and resumed. Generators are also very closely related to iterators, in the sense that a generator object is an iterator.&lt;/p&gt;

&lt;h2&gt;
  
  
  Comparison; Generators and Functions
&lt;/h2&gt;

&lt;p&gt;A regular function such as the one below cannot be stopped before it finishes its task i.e. its last line is executed. It follows something called the &lt;a href="https://en.wikipedia.org/wiki/Run_to_completion_scheduling" rel="noopener noreferrer"&gt;run-to-completion&lt;/a&gt; model.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function regularFunction() {
  console.log('There')
  console.log('is')
  console.log('no')
  console.log('stopping')
  console.log('me')
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The only way to exit the &lt;code&gt;regularFunction&lt;/code&gt; is by using a &lt;code&gt;return&lt;/code&gt; statement or throwing an error. If you call the function again, it will begin the execution from the top again.&lt;/p&gt;

&lt;p&gt;In contrast, a generator is a function that can stop midway and then continue from where it stopped. See the illustration below;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmebzdogaxiktr41gtn6e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmebzdogaxiktr41gtn6e.png" alt="Functions vs Generators"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Syntax
&lt;/h2&gt;

&lt;p&gt;Generator functions are created using a special syntax by adding an * after the &lt;code&gt;function&lt;/code&gt; keyword just like this &lt;code&gt;function *&lt;/code&gt;, and can be paused using the &lt;code&gt;yield&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;Calling a generator function initially does not execute any of its code; instead, it returns a generator object. Code is only executed and values are returned only when the generator’s &lt;code&gt;next()&lt;/code&gt; is called, which then executes code until it encounters the &lt;code&gt;yield&lt;/code&gt; keyword, upon which it pauses, until &lt;code&gt;next()&lt;/code&gt; is called again.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function * createGenerator() {
  yield 'This';
  yield 'is';
  yield 'a';
  yield 'Generator';
}
const generator = createGenerator(); // assigning the Generator function to the generator constant
generator.next(); // { value: 'This', done: false }
generator.next(); // { value: 'is', done: false }
generator.next(); // { value: 'a', done: false }
generator.next(); // { value: 'Generator', done: false }
generator.next(); // { value: undefined, done: true }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Calling &lt;code&gt;generator.next()&lt;/code&gt; repeatedly after our last statement above will only &lt;code&gt;return&lt;/code&gt; (or more accurately, &lt;code&gt;yield&lt;/code&gt;) the same &lt;code&gt;return&lt;/code&gt; object: &lt;code&gt;{ value: undefined, done: true }&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generators in Action
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Looping through an Array:
&lt;/h3&gt;

&lt;p&gt;Using a &lt;code&gt;for of&lt;/code&gt; loop we can iterate over our generator and &lt;code&gt;yield&lt;/code&gt; the content at each loop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// create an array of animals
const animalsList = ['Cat', 'Dog', 'Monkey', 'Bird', 'Fish'];

// create our looping generator
function* loop(arr) {
  for (const item of arr) {
    yield `I like a ${item} as a pet`;
  } 
}

const animalGenerator = loop(animalsList);
console.log(animalGenerator.next());
// Object { value: "I like a Cat as a pet", done: false }
console.log(animalGenerator.next());
// Object { value: "I like a Dog as a pet", done: false }
console.log(animalGenerator.next().value);
// "I like a Monkey as a pet"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our generator will now loop over the array and print one value at a time every time we call &lt;code&gt;.next()&lt;/code&gt;, To get only the value, then use &lt;code&gt;.next().value&lt;/code&gt; and it will not print the status of the generator.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;.return()&lt;/code&gt; in Generators
&lt;/h3&gt;

&lt;p&gt;With &lt;code&gt;.return()&lt;/code&gt; we can return a given value and finish the generator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* animalsList(){
  yield 'Cat';
  yield 'Dog';
  yield 'Monkey';
}

const animals = animalsList();

console.log(animals.return());
// Object { value: undefined, done: true }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We got &lt;code&gt;value: undefined&lt;/code&gt; because we did not pass anything in the &lt;code&gt;return()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;It’s not often you need generators. This article is just to provide a basic explanation of javascript generators. There is much more you can do with a generator, You can check out the official &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*" rel="noopener noreferrer"&gt;MDN documentation&lt;/a&gt; for more advanced cases where the use of generators can come in handy. &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
