<?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: Devansu Yadav</title>
    <description>The latest articles on DEV Community by Devansu Yadav (@devansuyadav).</description>
    <link>https://dev.to/devansuyadav</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%2F470174%2F764f3509-cb33-41fd-8a62-6bad2bf85ba7.jpg</url>
      <title>DEV Community: Devansu Yadav</title>
      <link>https://dev.to/devansuyadav</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/devansuyadav"/>
    <language>en</language>
    <item>
      <title>What the heck is a 'thunk' and what's 'Currying' ?!</title>
      <dc:creator>Devansu Yadav</dc:creator>
      <pubDate>Wed, 29 Jun 2022 16:31:07 +0000</pubDate>
      <link>https://dev.to/devansuyadav/what-the-heck-is-a-thunk-and-whats-currying-5fbe</link>
      <guid>https://dev.to/devansuyadav/what-the-heck-is-a-thunk-and-whats-currying-5fbe</guid>
      <description>&lt;p&gt;I'm quite sure the first term you'd heard of terms like &lt;code&gt;Thunks&lt;/code&gt; or &lt;code&gt;Currying&lt;/code&gt; in programming, your reaction would have been something similar to this,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/ghuvaCOI6GOoTX0RmH/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/ghuvaCOI6GOoTX0RmH/giphy.gif" alt="What?" width="480" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Well, don't worry, I felt the same when I heard about these terms the first time especially from the programming aspect until I realized how useful they are!&lt;/p&gt;

&lt;p&gt;Before we start, this blog post assumes that you have a basic knowledge of JavaScript and asynchronous programming using Promises and callbacks. Some knowledge about functional programming in JS would also be quite helpful to understand both these concepts better. &lt;strong&gt;Thunks&lt;/strong&gt; along with &lt;strong&gt;Currying&lt;/strong&gt; are quite useful concepts when it comes to &lt;strong&gt;Functional programming&lt;/strong&gt; in JavaScript.&lt;/p&gt;

&lt;p&gt;Let's dive deeper into these concepts and understand what they are, and how we can use them!&lt;/p&gt;

&lt;h2&gt;
  
  
  All about &lt;code&gt;thunks&lt;/code&gt; in JavaScript
&lt;/h2&gt;

&lt;p&gt;We have been using &lt;strong&gt;callbacks&lt;/strong&gt; in JavaScript almost everywhere for various use cases like &lt;strong&gt;asynchronous programming&lt;/strong&gt; , &lt;strong&gt;listening to events&lt;/strong&gt; , &lt;strong&gt;handling errors&lt;/strong&gt; , and much more. Thunks basically &lt;em&gt;extend the capabilities of callbacks&lt;/em&gt; and are quite useful when it comes to async programming in JavaScript, though they are still quite useful in certain scenarios involving synchronous programming.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a &lt;code&gt;thunk&lt;/code&gt;?
&lt;/h3&gt;

&lt;p&gt;A &lt;code&gt;thunk&lt;/code&gt; is just a function that delays the computation of a value or some logic.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The word "thunk" is a programming term that means "a piece of code that does some delayed work"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Rather than executing some logic &lt;em&gt;now, we can write a function body or code that can be used to perform the work later&lt;/em&gt;. Many of you working with &lt;code&gt;React&lt;/code&gt; probably know an awesome and plain simple library called &lt;code&gt;redux-thunk&lt;/code&gt; which as the name suggests is based on thunks, and is useful while doing state management using &lt;code&gt;Redux&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;There are two perspectives in which you can use &lt;code&gt;thunks&lt;/code&gt;: &lt;strong&gt;synchronous&lt;/strong&gt; , and &lt;strong&gt;asynchronous&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Synchronous way of using &lt;code&gt;thunks&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;Let's talk about how you can use a &lt;strong&gt;synchronous thunk&lt;/strong&gt; ,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const power = (base, exponent) =&amp;gt; {
  return Math.pow(base, exponent);
};

// `power` function is evaluated
// and the result is returned immediately
console.log(power(99, 9)); // 913517247483640800

// This is a thunk
const powerThunk = () =&amp;gt; {
  return power(99, 9);
};

// Returns the same result as calling the `power` function
console.log(powerThunk()); // 913517247483640800
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, &lt;code&gt;power&lt;/code&gt; is a simple function that calculates the power of a no and returns the calculated value immediately. &lt;code&gt;powerThunk&lt;/code&gt; is a &lt;strong&gt;synchronous thunk&lt;/strong&gt; that delays this result until we call it. As you might have noticed, &lt;code&gt;powerThunk&lt;/code&gt; uses the &lt;code&gt;power&lt;/code&gt; function internally to calculate and return the calculated value.&lt;/p&gt;

&lt;p&gt;The important part is that this thunk has become a wrapper around some particular state. In this case, it is a result of a potentially expensive operation. This pattern allows us to hide the internal details of the computation similar to the principle of &lt;a href="https://www.sumologic.com/glossary/encapsulation/#:~:text=What%20does%20encapsulation%20mean%3A%20In,in%20the%20form%20of%20classes."&gt;Encapsulation&lt;/a&gt; of the &lt;strong&gt;Object Oriented Programming&lt;/strong&gt; paradigm.&lt;/p&gt;

&lt;p&gt;Now let's talk about how you can use &lt;code&gt;thunks&lt;/code&gt; from the async programming perspective.&lt;/p&gt;

&lt;h3&gt;
  
  
  Async &lt;code&gt;thunks&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;So how can we describe an &lt;strong&gt;async thunk&lt;/strong&gt;? It's just a simple function that doesn't need any additional parameters except for a &lt;strong&gt;callback function&lt;/strong&gt;. In the case of async thunks, we can introduce a delay to process a synchronous function like the &lt;code&gt;power&lt;/code&gt; function from the previous example or use it to handle asynchronous API calls.&lt;/p&gt;

&lt;p&gt;Let's have a look at both cases. We can modify the previous example for &lt;strong&gt;synchronous thunk&lt;/strong&gt; to understand this better.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const powerAsync = (base, exponent, callback) =&amp;gt; {
  return setTimeout(() =&amp;gt; callback(Math.pow(base, exponent)), 1000);
};

// This is an async thunk
const powerAsyncThunk = (callback) =&amp;gt; {
  return function () {
    powerAsync(99, 9, callback);
  };
};

// This async thunk now returns a function that 
// can be called later on to calculate power.
const calculatePower = powerAsyncThunk((result) =&amp;gt; console.log(result));
calculatePower();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, we modified the &lt;code&gt;power&lt;/code&gt; function to &lt;code&gt;powerAsync&lt;/code&gt; function that &lt;strong&gt;fakes an asynchronous function&lt;/strong&gt; using &lt;code&gt;setTimeout&lt;/code&gt; and takes an additional parameter &lt;code&gt;callback&lt;/code&gt;. Now, our async thunk &lt;code&gt;powerAsyncThunk&lt;/code&gt; delays the execution of &lt;code&gt;powerAsync&lt;/code&gt; function by returning a function. This makes it really useful as we can now just call this function returned by &lt;code&gt;powerAsyncThunk&lt;/code&gt; whenever we want in our code later on.&lt;/p&gt;

&lt;p&gt;Now, let's talk about how we can deal with &lt;strong&gt;asynchronous API calls&lt;/strong&gt; using &lt;strong&gt;async thunks&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetchCurrenciesData = (callback) =&amp;gt; {
  fetch("https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json")
  .then(res =&amp;gt; res.json())
  .then(res =&amp;gt; callback(res));
}

// This is an async thunk
const asyncThunk = (callback) =&amp;gt; {
  return function () {
    fetchCurrenciesData(callback);
  }
}

// This async thunk now returns a function that 
// can be called later on to fetch data from the API.
const fetchCurrencies = asyncThunk((res) =&amp;gt; console.log(res));
fetchCurrencies();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;fetchCurrenciesData&lt;/code&gt; function makes an API call to fetch all the currencies of different countries and also takes a &lt;code&gt;callback&lt;/code&gt; function as a parameter. The async thunk &lt;code&gt;asyncThunk&lt;/code&gt; returns a function that can be called later on to fetch the data from the API whenever we want in our code.&lt;/p&gt;

&lt;p&gt;The data after calling &lt;code&gt;fetchCurrencies&lt;/code&gt; function looks something like this,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
aave: "Aave"
ada: "Cardano"
aed: "United Arab Emirates Dirham"
afn: "Afghan afghani"
algo: "Algorand"
doge: "Dogecoin"
dop: "Dominican peso"
dot: "Dotcoin"
dzd: "Algerian dinar"
egld: "Elrond"
egp: "Egyptian pound"
enj: "Enjin Coin"
eos: "EOS"
ern: "Eritrean nakfa"
etb: "Ethiopian birr"
ils: "Israeli New Shekel"
imp: "CoinIMP"
inj: "Injective"
inr: "Indian rupee"
iqd: "Iraqi dinar"
irr: "Iranian rial"
isk: "Icelandic krna"
jep: "Jersey Pound"
jmd: "Jamaican dollar"
jod: "Jordanian dinar"
jpy: "Japanese yen"
kava: "Kava"
kcs: "Kucoin"
kda: "Kadena"
kes: "Kenyan shilling"
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Where exactly are &lt;code&gt;thunks&lt;/code&gt; used? 💡
&lt;/h3&gt;

&lt;p&gt;Now that you have learned quite a lot about thunks, you might be wondering where exactly are &lt;strong&gt;thunks&lt;/strong&gt; used.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Promises&lt;/strong&gt; in JavaScript are based on the concept of &lt;strong&gt;thunks&lt;/strong&gt; and under the hood it uses thunks. Have a look at this &lt;a href="https://youtu.be/EhyuWntGA8s"&gt;video&lt;/a&gt; which talks about how &lt;strong&gt;thunks&lt;/strong&gt; can be used to sequence async function calls.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;a href="https://github.com/reduxjs/redux-thunk"&gt;redux-thunk&lt;/a&gt; middleware widely &lt;strong&gt;uses thunks internally&lt;/strong&gt;. This enables us to use &lt;strong&gt;thunks&lt;/strong&gt; with async logic inside, that can &lt;strong&gt;interact with a Redux store's&lt;/strong&gt; &lt;code&gt;dispatch&lt;/code&gt; and &lt;code&gt;getState&lt;/code&gt; methods for React apps using &lt;strong&gt;Redux&lt;/strong&gt; for state management.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  All about &lt;strong&gt;Currying&lt;/strong&gt; in JavaScript
&lt;/h2&gt;

&lt;p&gt;Let's look at another quite useful concept within functional programming in JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/BpGWitbFZflfSUYuZ9/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/BpGWitbFZflfSUYuZ9/giphy.gif" alt="Let's do this!" width="480" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Currying&lt;/strong&gt; is an advanced technique for working with functions. Its used not only in JavaScript but in other languages as well!&lt;/p&gt;

&lt;h3&gt;
  
  
  What is &lt;strong&gt;currying&lt;/strong&gt;?
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Currying&lt;/strong&gt; is a transformation of functions that converts a function from callable as &lt;code&gt;f(a, b, c)&lt;/code&gt; into callable as &lt;code&gt;f(a)(b)(c)&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We are transforming the function by breaking it down in such a way that it can be called in a step-by-step manner instead of calling it with all the arguments immediately. This technique is very useful, particularly when you don't have access to all the required parameters at an instant to be able to execute the logic inside your function.&lt;/p&gt;

&lt;p&gt;Let's look at an example to understand this better. Suppose, we create a simple function &lt;code&gt;multiplyTwoNos&lt;/code&gt; that multiplies two nos and returns the calculated value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multiplyTwoNos = (no1, no2) =&amp;gt; {
  return no1 * no2;
};

console.log(multiplyTwoNos(3, 5)); // 15

// A curried function to multiple two nos
const curriedMultiplyTwoNos = function (no1) {
  return function (no2) {
    return no1 * no2;
  };
};

console.log(curriedMultiplyTwoNos(3)(5)); // 15
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, &lt;code&gt;curriedMultiplyTwoNos&lt;/code&gt; is a function that uses &lt;strong&gt;currying&lt;/strong&gt; to transform &lt;code&gt;multiplyTwoNos(3, 5)&lt;/code&gt; function call to a function call something like this - &lt;code&gt;curriedMultiplyTwoNos(3)(5)&lt;/code&gt;. The output is basically the same, but &lt;strong&gt;currying&lt;/strong&gt; gives us more flexibility to calculate the multiplication of two numbers whenever we have access to both the numbers.&lt;/p&gt;

&lt;h3&gt;
  
  
  Advanced Currying Implementation
&lt;/h3&gt;

&lt;p&gt;Now, let's have a look at a bit more &lt;strong&gt;advanced implementation&lt;/strong&gt; of &lt;strong&gt;currying&lt;/strong&gt; for multi-argument functions. We'll first create a generic &lt;strong&gt;currying&lt;/strong&gt; function and then use the above example of multiplying some numbers and getting the calculated value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// A function that takes a callback function `func` 
// that defines the kind of operation/calculation that will be curried

const curry = function (func) {
  return function curried (...args) {
    // Ensure that we apply the operation defined by `func` 
    // with the max number of arguments supported by `func`.

    if(args.length &amp;gt;= func.length) {
      return func.apply(this, args);
    } else {
      // If number of parameters are insufficient to call `func` to 
      // perform the operation, recursively call `curried` with previously passed
      // parameters as well as new parameters. 
      return function (...args2) {
        return curried.apply(this, args.concat(args2));
      }
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are a lot of things happening in the above code! 😅 &lt;a href="https://i.giphy.com/media/NRXleEopnqL3a/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/NRXleEopnqL3a/giphy.gif" alt="Overwhelmed!" width="260" height="195"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But, don't get overwhelmed by seeing the above code, it's actually quite straightforward! Let's see how it works with an example and then we'll understand it properly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multiplyThreeNos = (no1, no2, no3) =&amp;gt; {
  return no1 * no2 * no3;
};

let curriedMultiplication = curry(multiplyThreeNos);

console.log(curriedMultiplication(4, 5, 6)); // 120, still callable normally
console.log(curriedMultiplication(4)(5, 6)); // 120, currying of 1st arg
console.log(curriedMultiplication(4)(5)(6)); // 120, full currying
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result of &lt;code&gt;curry(func)&lt;/code&gt; call is the wrapper &lt;code&gt;curried&lt;/code&gt; that looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function curried(...args) {
    // Ensure that we apply the operation defined by `func`
    // with the max number of arguments supported by `func`.

    if (args.length &amp;gt;= func.length) {
      return func.apply(this, args);
    } else {
      // If number of parameters are insufficient to call `func` to
      // perform the operation, recursively call `curried` with previously passed
      // parameters as well as new parameters.
      return function (...args2) {
        return curried.apply(this, args.concat(args2));
      };
    }
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we are using some of the concepts like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters"&gt;rest parameters&lt;/a&gt;, &lt;strong&gt;Recursions&lt;/strong&gt; , and &lt;a href="https://www.freecodecamp.org/news/understand-call-apply-and-bind-in-javascript-with-examples/"&gt;.apply()&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There are basically two branches of code out of which one of them could get executed within the &lt;code&gt;curried&lt;/code&gt; function because of the &lt;code&gt;if&lt;/code&gt; statement.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If the number of arguments passed to &lt;code&gt;curried&lt;/code&gt; is &lt;strong&gt;greater than or equal to&lt;/strong&gt; the no of arguments defined for &lt;code&gt;func&lt;/code&gt;, then just pass the call to &lt;code&gt;func.apply(this, args);&lt;/code&gt; which will execute ignore the extra arguments passed if any.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Else if the no of arguments passed to &lt;code&gt;curried&lt;/code&gt; is less, then we recursively call &lt;code&gt;curried&lt;/code&gt; with &lt;strong&gt;previously passed arguments&lt;/strong&gt; as well as the &lt;strong&gt;new arguments&lt;/strong&gt; by using the &lt;code&gt;.concat()&lt;/code&gt; method until the number of arguments for &lt;code&gt;curried&lt;/code&gt; is not sufficient as per the definition of &lt;code&gt;func&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; : &lt;strong&gt;Currying&lt;/strong&gt; requires the function to have a &lt;strong&gt;fixed number of arguments&lt;/strong&gt;. A function that uses rest parameters, such as &lt;code&gt;f(...args)&lt;/code&gt;, cant be curried this way as implemented above.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  When and Why to use &lt;strong&gt;Currying&lt;/strong&gt;? 💡
&lt;/h3&gt;

&lt;p&gt;Currying can be useful for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Currying can be used when you want to create a function that will receive only single arguments or will receive arguments later on in your code.&lt;/li&gt;
&lt;li&gt;It can be used to trigger event listeners.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's look at some of the reasons why you may need to use Currying:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Currying provides a way to make sure that your function receives all the arguments before you proceed with executing the core logic of your function.&lt;/li&gt;
&lt;li&gt;It divides your function into multiple smaller functions that can handle one responsibility. This makes your function pure and less prone to errors and side effects.&lt;/li&gt;
&lt;li&gt;It is used in the functional programming paradigm to create &lt;a href="https://dmitripavlutin.com/javascript-higher-order-functions/"&gt;higher-order functions&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this blog, we learned about &lt;strong&gt;Thunks&lt;/strong&gt; &amp;amp; &lt;strong&gt;Currying&lt;/strong&gt; , some of the most useful yet a bit advanced concepts of functional programming in JavaScript. We talked about &lt;strong&gt;thunks&lt;/strong&gt; in detail like what are &lt;strong&gt;thunks&lt;/strong&gt; , how can you use them, when to use them, and where are they used. Similarly, we learned about &lt;strong&gt;Currying&lt;/strong&gt; , how to implement &lt;strong&gt;currying&lt;/strong&gt; , &lt;strong&gt;advanced implementation&lt;/strong&gt; of &lt;strong&gt;currying&lt;/strong&gt; , and when to use it.&lt;/p&gt;

&lt;p&gt;That's it from me folks, thank you so much for reading this blog! 🙌 I hope this blog was helpful and gave you an insight about &lt;strong&gt;Thunks&lt;/strong&gt; &amp;amp; &lt;strong&gt;Currying&lt;/strong&gt; and how you could use these very useful concepts of the functional programming paradigm in your JavaScript apps 😄&lt;/p&gt;

&lt;p&gt;Before we end, &lt;a href="https://i.giphy.com/media/d3yvDeQ9fES0JTfG/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/d3yvDeQ9fES0JTfG/giphy.gif" alt="Excelsior!" width="480" height="345"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Feel free to reach out to me:&lt;br&gt;
&lt;a href="https://twitter.com/DevanshYtweets"&gt;Twitter&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.linkedin.com/in/devansu-yadav/"&gt;Linkedin&lt;/a&gt;&lt;br&gt;
&lt;a href="https://github.com/Devansu-Yadav"&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Make your React Apps more performant using Debouncing &amp; Throttling! 🔥🚀</title>
      <dc:creator>Devansu Yadav</dc:creator>
      <pubDate>Tue, 28 Jun 2022 12:14:58 +0000</pubDate>
      <link>https://dev.to/devansuyadav/make-your-react-apps-more-performant-using-debouncing-throttling-5e1d</link>
      <guid>https://dev.to/devansuyadav/make-your-react-apps-more-performant-using-debouncing-throttling-5e1d</guid>
      <description>&lt;p&gt;Well, hello there! 👋 I see you have come here to learn more about how to make your React apps performant and optimize them using Debouncing and Throttling, which is great because that means you really do care about your app's performance. Kudos for that! 👏&lt;/p&gt;

&lt;p&gt;Do note that this blog assumes that you have a &lt;strong&gt;basic understanding of how React works&lt;/strong&gt; and that you are familiar with &lt;strong&gt;React Hooks&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Before we jump in, let's understand why would you want to optimize your React app's performance?&lt;/p&gt;

&lt;p&gt;Suppose you have a very simple React app with an input bar to search cities like the below,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---udWTaPw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1656333065703/-Af0jIB_I.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---udWTaPw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1656333065703/-Af0jIB_I.gif" alt="Debouncing-Throttling-demo-1.gif" width="880" height="404"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, this app is super laggy and the UX of this app is 💩. We are just making a very simple search that filters cities from a list of cities based on user input.&lt;/p&gt;

&lt;p&gt;PS:- You can give it a try if you want (Please do it at your own risk, you don't wanna hang your computer!) - &lt;a href="https://codesandbox.io/s/debouncing-example-demo-0dyb16?file=/src/App.jsx"&gt;https://codesandbox.io/s/debouncing-example-demo-0dyb16?file=/src/App.jsx&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Now, you might ask why's this React app so laggy?
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/dXICCcws9oxxK/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/dXICCcws9oxxK/giphy.gif" alt="Why's the app super laggy?" width="540" height="250"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you would have noticed carefully from the above demo of the app, we are filtering the cities from the list of cities that we have on every keystroke made by the user (notice the keystrokes on the Virtual keyboard in the demo).&lt;/p&gt;

&lt;p&gt;See now, that's not a performant app at all and needs to be optimized to provide a better user experience.&lt;/p&gt;

&lt;p&gt;Let's have a look at two ways to optimize such apps and make them better!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/BpGWitbFZflfSUYuZ9/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/BpGWitbFZflfSUYuZ9/giphy.gif" alt="Let's make our React apps better" width="480" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Debouncing &amp;amp; Throttling?
&lt;/h2&gt;

&lt;p&gt;There are many scenarios that make your app less performant like making API calls on each user keystroke on an input search bar, performing compute-heavy operations on button clicks, window resizing, or frequent scrolls on a scrollbar.&lt;/p&gt;

&lt;p&gt;Basically, any scenario in which you are making expensive (in terms of computing or execution time) function calls on events or user actions that can hamper the performance of your apps.&lt;/p&gt;

&lt;p&gt;Now, let's understand &lt;strong&gt;Debouncing&lt;/strong&gt; &amp;amp; &lt;strong&gt;Throttling&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Debouncing&lt;/strong&gt; : In debouncing, we try to reduce the number of expensive function calls by calling them &lt;strong&gt;only if the time difference between two consecutive event triggers&lt;/strong&gt; (user actions) is &lt;strong&gt;greater than or equal&lt;/strong&gt; to a &lt;strong&gt;specified delay&lt;/strong&gt;. This &lt;strong&gt;delay&lt;/strong&gt; can be adjusted depending on the &lt;strong&gt;use case&lt;/strong&gt; or the kind of &lt;strong&gt;user experience&lt;/strong&gt; you are trying to design for your app.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Throttling&lt;/strong&gt; : In throttling, we try to &lt;strong&gt;rate-limit&lt;/strong&gt; the number of expensive function calls by calling them every time &lt;strong&gt;only after a certain time limit&lt;/strong&gt; has passed from the &lt;strong&gt;last function call&lt;/strong&gt;. Again, this time limit can be adjusted depending on your use case.&lt;/p&gt;

&lt;p&gt;Debouncing &amp;amp; Throttling can be very useful to handle &lt;strong&gt;rate-limit errors&lt;/strong&gt; caused by &lt;strong&gt;rate-limiting&lt;/strong&gt; on certain APIs that your apps might be consuming, as we are trying to reduce the number of such expensive function calls using these optimizations.&lt;/p&gt;

&lt;p&gt;Now that you have some idea about Debouncing &amp;amp; Throttling, let's dive deeper into each concept using a simple example that illustrates some of their common use cases.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/xT39Db8zIOODTppk08/giphy-downsized-large.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/xT39Db8zIOODTppk08/giphy-downsized-large.gif" alt="let's do this!" width="296" height="296"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Optimizing apps using Debouncing
&lt;/h3&gt;

&lt;p&gt;Let's go back to the very first example that we saw, where we had a simple search bar that filters the cities from a list of cities based on the user input.&lt;/p&gt;

&lt;p&gt;We can use &lt;strong&gt;debouncing&lt;/strong&gt; in this case to reduce the number of function calls to filter the cities from the list.&lt;/p&gt;

&lt;p&gt;But first, let's look at the initial code from the demo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initial Code&lt;/strong&gt; -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./styles.css";
import React, { useState } from "react";
import cities from "cities-list";
import { v4 as uuidv4 } from "uuid";

// An array of city names
const citiesArray = Object.keys(cities);

export default function App() {
  const [cityInput, setCityInput] = useState("");
  const [filteredCities, setFilteredCities] = useState([]);

  // Function that filters cities from the list based on user input
  const cityFilter = (query) =&amp;gt; {
    console.log(query);
    if (!query) return setFilteredCities([]);

    setFilteredCities(
      citiesArray.filter((city) =&amp;gt;
        city.toLowerCase().includes(query.toLowerCase())
      )
    );
  };

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;h1 className="app-header"&amp;gt;Find cities&amp;lt;/h1&amp;gt;
      &amp;lt;div className="city-input"&amp;gt;
        &amp;lt;input
          type="text"
          value={cityInput}
          onChange={(e) =&amp;gt; {
            setCityInput(e.target.value);
            cityFilter(e.target.value);
          }}
        /&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        {filteredCities.map((city) =&amp;gt; {
          return &amp;lt;div key={uuidv4()}&amp;gt;{city}&amp;lt;/div&amp;gt;;
        })}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;The above code snippet represents a &lt;strong&gt;simple React component&lt;/strong&gt; with an &lt;strong&gt;input search bar&lt;/strong&gt; , and a &lt;strong&gt;container that displays the filtered cities&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Function that filters cities from the list based on user input
  const cityFilter = (query) =&amp;gt; {
    console.log(query);
    if (!query) return setFilteredCities([]);

    setFilteredCities(
      citiesArray.filter((city) =&amp;gt;
        city.toLowerCase().includes(query.toLowerCase())
      )
    );
  };

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

&lt;/div&gt;



&lt;p&gt;The function &lt;code&gt;cityFilter&lt;/code&gt; takes a &lt;strong&gt;user search query&lt;/strong&gt; as an input parameter and filters the cities from a list of cities (fetched from an npm package called &lt;code&gt;cities-list&lt;/code&gt;). Currently, this function runs on every single keystroke made by the user on the search bar.&lt;/p&gt;

&lt;p&gt;Now, let's write a &lt;strong&gt;debounced version&lt;/strong&gt; of the above &lt;code&gt;cityFilter&lt;/code&gt; function to make it more optimal. We will be using &lt;code&gt;setTimeout&lt;/code&gt; in JavaScript to achieve this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// `timer` to help while clearing setTimeout 
// inside `debouncedCityFilter` function
let timer;

// Debounced version of the `cityFilter` func to filter cities 
// based on user search query
  const debouncedCityFilter = (query) =&amp;gt; {
    clearTimeout(timer);
    if (!query) return setFilteredCities([]);

    timer = setTimeout(() =&amp;gt; {
      console.log(query);

      setFilteredCities(
        citiesArray.filter((city) =&amp;gt;
          city.toLowerCase().includes(query.toLowerCase())
        )
      );
    }, 500);
  };

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

&lt;/div&gt;



&lt;p&gt;According to the concept of debouncing, we make function calls only if the &lt;strong&gt;time difference between two consecutive event triggers&lt;/strong&gt; (user actions) is &lt;strong&gt;greater than or equal&lt;/strong&gt; to a specified delay.&lt;/p&gt;

&lt;p&gt;In the above code snippet, we set the state to get the filtered cities using &lt;code&gt;setFilteredCities()&lt;/code&gt; which is called inside a &lt;code&gt;setTimeout&lt;/code&gt; with a delay of &lt;code&gt;500ms&lt;/code&gt;(this delay can be adjusted according to the use case). So whenever a user keystroke is recorded on the input search bar, the &lt;code&gt;debouncedCityFilter&lt;/code&gt; function is called which triggers &lt;code&gt;setTimeout&lt;/code&gt; and sets the state using &lt;code&gt;setFilteredCities()&lt;/code&gt; after &lt;code&gt;500ms&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;However, if another keystroke made by the user is recorded just within this time delay of &lt;code&gt;500ms&lt;/code&gt;, the previous &lt;code&gt;setTimeout&lt;/code&gt; needs to be cleared to avoid filtering the cities and set the state. For this, we use &lt;code&gt;clearTimeout&lt;/code&gt; that takes the &lt;code&gt;id&lt;/code&gt; returned by the &lt;code&gt;setTimeout&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Now, this &lt;code&gt;id&lt;/code&gt; needs to be preserved so that it is available whenever we need to use &lt;code&gt;clearTimeout&lt;/code&gt; to clear the timer. We use a quite popular concept called &lt;a href="https://www.freecodecamp.org/news/lets-learn-javascript-closures-66feb44f6a44/"&gt;Closures&lt;/a&gt; in JavaScript to be able to access this &lt;code&gt;id&lt;/code&gt; inside the &lt;code&gt;debouncedCityFilter&lt;/code&gt; function. Hence, if you'd have noticed we have defined a &lt;code&gt;timer&lt;/code&gt; variable outside the &lt;code&gt;debouncedCityFilter&lt;/code&gt; function for use inside this function.&lt;/p&gt;

&lt;p&gt;By simply debouncing the &lt;code&gt;cityFilter&lt;/code&gt; function, we are able to reduce the number of function calls and hence able to improve the performance significantly of our React app.&lt;/p&gt;

&lt;p&gt;Let's have a look at what our React component code looks like after making these changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Final Code&lt;/strong&gt; -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./styles.css";
import React, { useState } from "react";
import cities from "cities-list";
import { v4 as uuidv4 } from "uuid";

// An array of city names
const citiesArray = Object.keys(cities);

// `timer` to help while clearing setTimeout 
// inside `debouncedCityFilter` function
let timer;

export default function App() {
  const [cityInput, setCityInput] = useState("");
  const [filteredCities, setFilteredCities] = useState([]);

  // Function that filters cities from the list based on user input
  const cityFilter = (query) =&amp;gt; {
    console.log(query);
    if (!query) return setFilteredCities([]);

    setFilteredCities(
      citiesArray.filter((city) =&amp;gt;
        city.toLowerCase().includes(query.toLowerCase())
      )
    );
  };

  // Debounced version of the `cityFilter` func to filter 
  // cities based on user search query
  const debouncedCityFilter = (query) =&amp;gt; {
    clearTimeout(timer);
    if (!query) return setFilteredCities([]);

    timer = setTimeout(() =&amp;gt; {
      console.log(query);

      setFilteredCities(
        citiesArray.filter((city) =&amp;gt;
          city.toLowerCase().includes(query.toLowerCase())
        )
      );
    }, 500);
  };

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;h1 className="app-header"&amp;gt;Find cities&amp;lt;/h1&amp;gt;
      &amp;lt;div className="city-input"&amp;gt;
        &amp;lt;input
          type="text"
          value={cityInput}
          onChange={(e) =&amp;gt; {
            setCityInput(e.target.value);
            debouncedCityFilter(e.target.value);
          }}
        /&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        {filteredCities.map((city) =&amp;gt; {
          return &amp;lt;div key={uuidv4()}&amp;gt;{city}&amp;lt;/div&amp;gt;;
        })}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;Now, have a look at how debouncing has improved the performance of this component significantly! 🚀&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/debouncing-example-demo-0dyb16"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;If you want to handle more edge cases for debouncing such functions, then you can check out &lt;a href="https://lodash.com/"&gt;Lodash&lt;/a&gt; which has a &lt;code&gt;debounce&lt;/code&gt; method that covers most of the edge cases involved to make such functions more optimal.&lt;/p&gt;

&lt;p&gt;Now, let's look at a simple example that uses Throttling to make it more performant.&lt;/p&gt;

&lt;h3&gt;
  
  
  Optimizing apps using Throttling
&lt;/h3&gt;

&lt;p&gt;Let's suppose, you have a simple React component consisting of a &lt;code&gt;button&lt;/code&gt; that on clicking &lt;strong&gt;calls an API&lt;/strong&gt; to fetch some data related to all the currencies of different countries.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initial Code&lt;/strong&gt; -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./styles.css";
import React, { useState } from "react";
import axios from "axios";
import { v4 as uuid } from "uuid";

export default function App() {
  const [currencyData, setCurrencyData] = useState({});
  const [clickCounter, setClickCounter] = useState(0);

  const getCurrencyData = async () =&amp;gt; {
    console.log("Fetching data ....");

    const { data } = await axios.get(
      "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json"
    );

    // Fetching only 15 currencies for now
    const countryCurrencies = {};
    const currencyObjKeys = Object.keys(data).slice(0, 15);

    currencyObjKeys.forEach((key) =&amp;gt; {
      countryCurrencies[key] = data[key];
    });

    setCurrencyData({ ...countryCurrencies });
  };

  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;h1&amp;gt;Currencies of different Countries&amp;lt;/h1&amp;gt;
      &amp;lt;button
        className="currency-btn"
        onClick={() =&amp;gt; {
          setClickCounter((clickCount) =&amp;gt; clickCount + 1);
          getCurrencyData();
        }}
      &amp;gt;
        Click to get all currencies
      &amp;lt;/button&amp;gt;
      &amp;lt;span&amp;gt;Btn clicked - {clickCounter} times&amp;lt;/span&amp;gt;
      &amp;lt;div className="currencies"&amp;gt;
        {Object.keys(currencyData).map((currency) =&amp;gt; {
          return (
            &amp;lt;div key={uuid()}&amp;gt;
              {currency}: {currencyData[currency]}
            &amp;lt;/div&amp;gt;
          );
        })}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;The code snippet above is our simple component with two states - &lt;code&gt;currencyData&lt;/code&gt; &amp;amp; &lt;code&gt;clickCounter&lt;/code&gt;. On button click, we update the &lt;code&gt;clickCounter&lt;/code&gt; state to reflect the total number of button clicks made so far and also call the &lt;code&gt;getCurrencyData()&lt;/code&gt; function to make an API call to fetch the currency data.&lt;/p&gt;

&lt;p&gt;Let's look at what this component looks like!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0yrnyV4D--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1656412297772/DeZ8Hoab5.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0yrnyV4D--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1656412297772/DeZ8Hoab5.gif" alt="Debouncing-&amp;amp;-Throttling-demo-2.gif" width="880" height="404"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you might have noticed above, each button click triggers an API call. Now, imagine that your app was used by hundreds or thousands of users, the number of API calls would be humongous! Your Back-End servers could face a huge pool of requests coming from each user due to so many clicks. Also, if you are consuming any external paid API or service, then the endpoints might start throwing errors because of &lt;strong&gt;rate-limiting&lt;/strong&gt; on the API endpoints.&lt;/p&gt;

&lt;p&gt;Even if say you were not making any API calls on such button clicks but rather performing some &lt;strong&gt;compute-heavy&lt;/strong&gt; operation, it would hamper your app's performance severely!&lt;/p&gt;

&lt;p&gt;Now, that's a bit of a problem 😅 &lt;a href="https://i.giphy.com/media/1Y7ChRtbWnYONjDidg/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/1Y7ChRtbWnYONjDidg/giphy.gif" alt="Time to solve some problems!" width="189" height="177"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's try and solve this problem using Throttling!&lt;/p&gt;

&lt;p&gt;We will throttle the &lt;code&gt;getCurrencyData&lt;/code&gt; function that makes an API call on each button click.&lt;/p&gt;

&lt;p&gt;Currently, the code for &lt;code&gt;getCurrencyData&lt;/code&gt; looks like this,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getCurrencyData = async () =&amp;gt; {
    console.log("Fetching data ....");

    const { data } = await axios.get(
      "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json"
    );

    // Fetching only 15 currencies for now
    const countryCurrencies = {};
    const currencyObjKeys = Object.keys(data).slice(0, 15);

    currencyObjKeys.forEach((key) =&amp;gt; {
      countryCurrencies[key] = data[key];
    });

    setCurrencyData({ ...countryCurrencies });
  };

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

&lt;/div&gt;



&lt;p&gt;Now, we will write a function &lt;code&gt;throttledGetCurrencyData&lt;/code&gt; that will throttle and use the &lt;code&gt;getCurrencyData&lt;/code&gt; function to reduce the number of calls made to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// A flag to control the function calls to the `getCurrencyData` function
let shouldFuncBeCalled = true;

const throttledGetCurrencyData = async () =&amp;gt; {
    if (shouldFuncBeCalled) {
      await getCurrencyData();
      shouldFuncBeCalled = false;

      setTimeout(() =&amp;gt; {
        shouldFuncBeCalled = true;
      }, 500);
    }
  };

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

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;throttledGetCurrencyData&lt;/code&gt; function calls the &lt;code&gt;getCurrencyData&lt;/code&gt; function only if the &lt;code&gt;shouldFuncBeCalled&lt;/code&gt; flag is set to &lt;code&gt;true&lt;/code&gt;. Once this function is called, we delay the next function call to the &lt;code&gt;getCurrencyData&lt;/code&gt; function by using &lt;code&gt;setTimeout&lt;/code&gt; with some specific delay (This delay limit can be adjusted as per your use case).&lt;/p&gt;

&lt;p&gt;This way we only allow function calls to happen after a certain amount of time has passed from the last function call. This way we can avoid making the UI slow or crossing the rate limits defined for any API that your app might be consuming.&lt;/p&gt;

&lt;p&gt;Let's look at how the app is working now.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0pt1z8Pf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1656414439574/RSIAQ7IHe.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0pt1z8Pf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1656414439574/RSIAQ7IHe.gif" alt="Debouncing-&amp;amp;-Throttling-demo-3.gif" width="880" height="404"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see from the console, the number of API calls has been reduced quite significantly even after clicking the button so many times!&lt;/p&gt;

&lt;p&gt;Check out the CodeSandbox below to see what the code for our component looks like after using Throttling.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/throttling-demo-solution-70o8ig"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;If you want to handle more edge cases for throttling such functions, then you can check out &lt;a href="https://lodash.com/"&gt;Lodash&lt;/a&gt; which has a &lt;code&gt;throttle&lt;/code&gt; method that covers most of the edge cases involved to make such functions more optimal.&lt;/p&gt;

&lt;h2&gt;
  
  
  Debouncing vs Throttling, when to use what?
&lt;/h2&gt;

&lt;p&gt;Now that we understand how Debouncing and Throttling work, let's understand some of the differences and when to use Debouncing or Throttling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Throttling&lt;/strong&gt; enforces that a function must be called every time after a certain amount of time (or delay) has passed from the last function call.&lt;/p&gt;

&lt;p&gt;Whereas, &lt;strong&gt;Debouncing&lt;/strong&gt; enforces that a function must only be called if a certain amount of time (or delay) has passed without it being called. If this time has not been passed the &lt;strong&gt;debounce timer&lt;/strong&gt; keeps &lt;strong&gt;resetting&lt;/strong&gt; and the &lt;strong&gt;function call is avoided&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  When to use what?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Search bar&lt;/strong&gt; : Use &lt;strong&gt;debouncing&lt;/strong&gt; to avoid searching every time a user hits a keystroke. &lt;strong&gt;Throttling&lt;/strong&gt; is not convenient here to use in this scenario, as you don't want to make your user wait too long for fetching the search results (in the worst case if the previous function call was made just when the user stops typing).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Shooting game&lt;/strong&gt; : Use &lt;strong&gt;throttling&lt;/strong&gt; on mouse click as shooting a pistol takes a few secs to register and it helps in avoiding the user to shoot until the previous shot has been registered. &lt;strong&gt;Debouncing&lt;/strong&gt; will not shoot a bullet until a certain amount of time has passed when the pistol was not fired.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can also check out this amazing &lt;a href="https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function"&gt;Stackoverflow post&lt;/a&gt; to understand the differences between &lt;strong&gt;Debouncing&lt;/strong&gt; &amp;amp; &lt;strong&gt;Throttling&lt;/strong&gt; and when to use what.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Debouncing&lt;/strong&gt; &amp;amp; &lt;strong&gt;Throttling&lt;/strong&gt; are just a few ways you can make your React apps more performant &amp;amp; each technique has its own set of pros and cons depending on the use cases. In this blog, we first talked about &lt;strong&gt;Why should we care about our React app's performance&lt;/strong&gt; , then we understood &lt;strong&gt;how we can use Debouncing &amp;amp; Throttling&lt;/strong&gt; to optimize our app's performance, and finally saw a &lt;strong&gt;major difference between the two techniques&lt;/strong&gt; and &lt;strong&gt;when we to use which technique&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;That's it from me folks, thank you so much for reading this blog! 🙌 I hope this blog was helpful and gave you an insight on how you can make your React apps more performant. Now, go ahead and make your apps even more amazing! 🚀&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/d3yvDeQ9fES0JTfG/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/d3yvDeQ9fES0JTfG/giphy.gif" alt="Until next time!" width="480" height="345"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Feel free to reach out to me:&lt;br&gt;
&lt;a href="https://twitter.com/DevanshYtweets"&gt;Twitter&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.linkedin.com/in/devansu-yadav/"&gt;Linkedin&lt;/a&gt;&lt;br&gt;
&lt;a href="https://github.com/Devansu-Yadav"&gt;GitHub&lt;/a&gt;&lt;br&gt;
You can also reach out to me over mail: &lt;a href="//mailto:devansuyadav@gmail.com"&gt;devansuyadav@gmail.com&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
      <category>programming</category>
    </item>
    <item>
      <title>Everything you need to know about Generators in JavaScript 🚀</title>
      <dc:creator>Devansu Yadav</dc:creator>
      <pubDate>Sat, 25 Jun 2022 17:11:19 +0000</pubDate>
      <link>https://dev.to/devansuyadav/everything-you-need-to-know-about-generators-in-javascript-2h5b</link>
      <guid>https://dev.to/devansuyadav/everything-you-need-to-know-about-generators-in-javascript-2h5b</guid>
      <description>&lt;p&gt;If you have been working with JavaScript quite a lot, you might have come across some syntax like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* makeIterator() {
    yield 1;
    yield 2;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, you might be wondering what is this code exactly doing? Well, honestly speaking, I felt the same when I came across such syntax for the first time! 😅&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/ne3xrYlWtQFtC/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/ne3xrYlWtQFtC/giphy.gif" alt="I don't understand" width="540" height="231"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This weird yet quite useful piece of code is what we call &lt;strong&gt;Generators&lt;/strong&gt; in JavaScript.&lt;/p&gt;

&lt;p&gt;Let's try and understand what are Generators, how to use them, and when to use them in your JavaScript code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Demystifying Iterators &amp;amp; Generators
&lt;/h2&gt;

&lt;p&gt;Now, before we try to understand generators, let's first understand the concept of &lt;strong&gt;Iterables&lt;/strong&gt; and &lt;strong&gt;Iterators&lt;/strong&gt; so that we can understand generators better.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iterables&lt;/strong&gt; : Iterables are basically &lt;strong&gt;data structures&lt;/strong&gt; that have the &lt;code&gt;Symbol.iterator()&lt;/code&gt; method or the &lt;code&gt;Symbol.iterator&lt;/code&gt; key. Some of the most commonly used data structures in JavaScript like Array, String, Set, and Map are examples of Iterables.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Symbol.iterator()&lt;/code&gt; method defines how these iterables can be iterated by using iterators and the &lt;code&gt;for...of&lt;/code&gt; loop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iterators&lt;/strong&gt; : An iterator is an object that is returned by the &lt;code&gt;Symbol.iterator()&lt;/code&gt; method. This object has a &lt;code&gt;next()&lt;/code&gt; method that returns an object with two properties:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;value&lt;/code&gt;: The value of the next element in the iteration sequence or the iterable.&lt;br&gt;&lt;br&gt;
&lt;code&gt;done&lt;/code&gt;: This is a boolean value. It is set to &lt;code&gt;true&lt;/code&gt; if the last element in the iteration sequence is already iterated else it is set to &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's see a simple example of how we can iterate through all the elements in the Array using a &lt;code&gt;for...of&lt;/code&gt; loop and an Array Iterator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const number = [1, 2, 3];
const arrayIterator = number[Symbol.iterator]();

console.log(arrayIterator);

// Iterating through the iterator to access array elements
for (let n of arrayIterator) {
    console.log(n);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array Iterator {}
1
2
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  So, what are generators?
&lt;/h3&gt;

&lt;p&gt;A generator is a process that can be paused and resumed and can yield multiple values. A generator in JavaScript consists of a Generator function, which returns an iterable &lt;code&gt;Generator&lt;/code&gt; object and this object is basically a special type of Iterator.&lt;/p&gt;

&lt;h3&gt;
  
  
  Now, what are generator functions?
&lt;/h3&gt;

&lt;p&gt;Let's have a look at a simple example of a generator function to understand it better.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Generator function declaration
function* generatorFunction() {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see above, a Generator function can be defined by using the &lt;code&gt;function&lt;/code&gt; keyword followed by an asterisk (&lt;code&gt;*&lt;/code&gt;). Occasionally, you will also see the asterisk next to the function name, as opposed to the function keyword, such as &lt;code&gt;function *generatorFunction()&lt;/code&gt;. This works the same, but &lt;code&gt;function*&lt;/code&gt; is generally a more widely accepted syntax.&lt;/p&gt;

&lt;p&gt;Generator functions can also be defined in regular function expressions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Generator function expression
const generatorFunction = function*() {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Why do we need to use Generators?
&lt;/h3&gt;

&lt;p&gt;We can define our own custom iterators for our specific use cases, so why should we even care about generators at all?&lt;/p&gt;

&lt;p&gt;There's an added complexity with &lt;strong&gt;custom iterators&lt;/strong&gt; that you have to carefully program them and also &lt;strong&gt;explicitly maintain their internal state&lt;/strong&gt; to know which elements have been iterated and when to stop the function execution.&lt;/p&gt;

&lt;p&gt;Generators provide a powerful alternative to custom iterators that allows you to define your own iteration algorithms using generator functions that do not execute code continuously.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/RN6OnheJ9ZEm4/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/RN6OnheJ9ZEm4/giphy.gif" alt="Powerful Generators!" width="500" height="198"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's look at how you can use these Generator functions &amp;amp; Generators for your specific use cases.&lt;/p&gt;

&lt;h2&gt;
  
  
  Working with Generator functions &amp;amp; Generators
&lt;/h2&gt;

&lt;p&gt;A generator function, when invoked, returns an iterable &lt;code&gt;Generator&lt;/code&gt; object which is basically nothing but a generator. A generator function differs from a traditional function JavaScript in that generator functions do not return a value immediately instead they return a &lt;code&gt;Generator&lt;/code&gt; object which is an iterator as we saw above.&lt;/p&gt;

&lt;p&gt;Let's have a look at an example to make this difference between generator functions and traditional functions clear.&lt;/p&gt;

&lt;p&gt;In the following code, we create a simple &lt;code&gt;power()&lt;/code&gt; function that calculates the &lt;strong&gt;power of a given number&lt;/strong&gt; by using &lt;strong&gt;two integer parameters&lt;/strong&gt; ( &lt;strong&gt;base no&lt;/strong&gt; and the &lt;strong&gt;exponent no&lt;/strong&gt; ) and returns this calculated value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// A regular function that calculates power of a no
function power(base, exponent) {
  return Math.pow(base, exponent);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, calling this function returns the power of the given no,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;power(2, 3); // 8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's create the same function above but as a generator function,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// A generator function that calculates power of a no
function* powerGeneratorFunction(base, exponent) {
  return Math.pow(base, exponent);
}

const powerGenerator = power(2, 3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, when we invoke the generator function, it will return the &lt;code&gt;Generator&lt;/code&gt; object which looks something like this,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;power {&amp;lt;suspended&amp;gt;}
[[GeneratorLocation]]: VM305:2
[[Prototype]]: Generator
[[GeneratorState]]: "suspended"
[[GeneratorFunction]]: * power(base, exponent)
[[GeneratorReceiver]]: Window
[[Scopes]]: Scopes[3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This &lt;code&gt;Generator&lt;/code&gt; object has a &lt;code&gt;next()&lt;/code&gt; method similar to Iterators. Let's call this method and see what we get,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Call the next method on the Generator object
powerGenerator.next();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will give the following output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ value: 8, done: true }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we saw earlier, a &lt;code&gt;Generator&lt;/code&gt; object is nothing but an Iterator, hence the &lt;code&gt;next()&lt;/code&gt; method returns something similar to Iterators i.e an object containing two properties, &lt;code&gt;value&lt;/code&gt; &amp;amp; &lt;code&gt;done&lt;/code&gt;. The power of &lt;code&gt;2&lt;/code&gt; raised to &lt;code&gt;3&lt;/code&gt; is &lt;code&gt;8&lt;/code&gt; which is reflected by &lt;code&gt;value&lt;/code&gt;. The value of &lt;code&gt;done&lt;/code&gt; is set to &lt;code&gt;true&lt;/code&gt; because this value came from a &lt;code&gt;return&lt;/code&gt; that closed out this generator.&lt;/p&gt;

&lt;p&gt;We saw how to create a simple generator function and how these functions work. Now let's have a look at some of the features of these generators that make them quite useful and unique.&lt;/p&gt;

&lt;h3&gt;
  
  
  The &lt;code&gt;yield&lt;/code&gt; operator
&lt;/h3&gt;

&lt;p&gt;Generators introduce a new keyword to JavaScript: &lt;code&gt;yield&lt;/code&gt;. The &lt;code&gt;yield&lt;/code&gt; operator can pause a generator function and return the value that follows &lt;code&gt;yield&lt;/code&gt;, providing a lightweight way to iterate through values.&lt;/p&gt;

&lt;p&gt;Let's have a look at an example to understand this better.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* simpleGeneratorFunction () {
  console.log("Before 1");
  yield 1;
  console.log("After 1");
  console.log("Before 2");
  yield 2;
  console.log("After 2");
  console.log("Before 3");
  yield 3;
  console.log("After 3");
}

const simpleGenerator = simpleGeneratorFunction();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code snippet, we have defined a simple generator function that contains 3 &lt;code&gt;yield&lt;/code&gt; statements. Now, let's call the &lt;code&gt;next()&lt;/code&gt; method to see how this &lt;code&gt;yield&lt;/code&gt; operator works.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Call the next() method four times
console.log(simpleGenerator.next());
console.log(simpleGenerator.next());
console.log(simpleGenerator.next());
console.log(simpleGenerator.next());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, when we call &lt;code&gt;next()&lt;/code&gt; on the generator function, it will pause every time it encounters &lt;code&gt;yield&lt;/code&gt;. The &lt;code&gt;done&lt;/code&gt; property will be set to &lt;code&gt;false&lt;/code&gt; after each &lt;code&gt;yield&lt;/code&gt;, indicating that the generator has not finished. Once we encounter a &lt;code&gt;return&lt;/code&gt; statement or if there are no more &lt;code&gt;yield&lt;/code&gt; statements left, then the &lt;code&gt;done&lt;/code&gt; property will be set to &lt;code&gt;true&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's look at the output after calling the &lt;code&gt;next()&lt;/code&gt; method &lt;strong&gt;four&lt;/strong&gt; times.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Before 1
{value: 1, done: false}
After 1
Before 2
{value: 2, done: false}
After 2
Before 3
{value: 3, done: false}
After 3
{value: undefined, done: true}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Iterating Over a Generator
&lt;/h3&gt;

&lt;p&gt;Using the &lt;code&gt;next()&lt;/code&gt; method, we manually iterated through the &lt;code&gt;Generator&lt;/code&gt; object, receiving all the &lt;code&gt;value&lt;/code&gt; and &lt;code&gt;done&lt;/code&gt; properties of the full object. We can iterate over a generator similar to how we can iterate over data structures like &lt;code&gt;Array&lt;/code&gt;, &lt;code&gt;Map&lt;/code&gt;, or &lt;code&gt;Set&lt;/code&gt; using a simple &lt;code&gt;for...of&lt;/code&gt; loop.&lt;/p&gt;

&lt;p&gt;Let's have a look at the above example and see how we can iterate over generators.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Creating a new Generator object.
const newGenerator = simpleGeneratorFunction();

// Iterating over the Generator object
for (const value of newGenerator) {
  console.log(value);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; : In the above code snippet, we initialized a new &lt;code&gt;Generator&lt;/code&gt; object as we had already manually iterated the older &lt;code&gt;Generator&lt;/code&gt; object &amp;amp; hence it can't be iterated again.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This code snippet now returns the following output,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Before 1
1
After 1
Before 2
2
After 2
Before 3
3
After 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we iterated through all the values of the &lt;code&gt;Generator&lt;/code&gt; object. Now, let's look at some of the use-cases of Generators and Generator functions.&lt;/p&gt;

&lt;h3&gt;
  
  
  Passing values in Generators
&lt;/h3&gt;

&lt;p&gt;Generators provide a way to pass custom values through the &lt;code&gt;next()&lt;/code&gt; method of the &lt;code&gt;Generator&lt;/code&gt; object to modify the internal state of the generator.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; : A value passed to &lt;code&gt;next()&lt;/code&gt; will be received by the &lt;code&gt;yield&lt;/code&gt; operator.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's take an example to understand this better.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Take three integers and return their sum
function* sumGeneratorFunction() {
  let sumOfThreeNos = 0;
  console.log(sumOfThreeNos);
  sumOfThreeNos += yield;
  console.log(sumOfThreeNos);
  sumOfThreeNos += yield;
  console.log(sumOfThreeNos);
  sumOfThreeNos += yield;
  console.log(sumOfThreeNos);

  return sumOfThreeNos;
}

const generator = sumGeneratorFunction();

generator.next();
generator.next(100);
generator.next(200);
generator.next(300);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will give the following output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0
100
300
600
{value: 600, done: true}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we are calculating the cumulative sum of three nos by passing them one by one by passing the value in the &lt;code&gt;next()&lt;/code&gt; method.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; : Passing a value to the first &lt;code&gt;next()&lt;/code&gt; method has no effect on the internal state of the generator. Values can be passed from the 2nd call to all the other subsequent calls to this method.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Uses of Generators and Generator functions
&lt;/h2&gt;

&lt;p&gt;Generators and Generator functions are quite powerful and have some really good use-cases.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/A9grgCQ0Dm012/giphy-downsized-large.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/A9grgCQ0Dm012/giphy-downsized-large.gif" alt="Power of Generators" width="448" height="252"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Generators provide a great way of making iterators and are capable of dealing with infinite data streams, which can be used to implement infinite scroll on the Front-End of a web application. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Generators when used with &lt;code&gt;Promise&lt;/code&gt; can be used to simulate &lt;code&gt;async/await&lt;/code&gt; functionality in JS to allow handling more advanced use-cases while dealing with APIs or asynchronous code. It allows us to work with asynchronous code in a simpler and more readable manner.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Generators are also internally used in some of the NPM libraries to provide a custom way for the developer to iterate through some of the objects/data structures implemented by the library. They are also used for internal asynchronous operations to handle more advanced use cases.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's discuss one of the major use-cases of Generators that you will most likely come across i.e dealing with &lt;strong&gt;infinite iterations&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;To demonstrate infinite streams, we consider a simple square number series in Mathematics where each term in the series can be calculated by a simple formula: &lt;code&gt;n^2&lt;/code&gt;. Let's create a generator function for this series by creating an infinite loop as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Create a square number series generator function
function* squareNumberSeries() {
  let n = 1;

  // Square the no and increment it to yield the infinite series
  while (true) {
    const squaredNo = Math.pow(n, 2);
    yield squaredNo;
    n += 1;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To test this out, we can loop through a finite number and print the Square number sequence to the console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Print the first 10 values of the square number series
const squareNoGenerator = squareNumberSeries();

for (let i = 0; i &amp;lt; 10; i++) {
  console.log(squareNoGenerator.next().value);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will generate the following series:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1
4
9
16
25
36
49
64
81
100
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;squareNumberSeries&lt;/code&gt; generator function in the above code snippet returns successive values in the infinite loop while the &lt;code&gt;done&lt;/code&gt; property remains false, ensuring that it will not finish. With generators, we dont need to worry about creating an infinite loop, because we can halt and resume its execution at will.&lt;/p&gt;

&lt;p&gt;However, we still have to take care with how we invoke the generator.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Using the spread operator or &lt;code&gt;for...of&lt;/code&gt; loop on an infinite data stream will cause it to keep iterating over an infinite loop all at once, which will cause the environment to crash.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Working with infinite data streams is one of the most powerful features that generators provide without worrying about managing all the internal states for a custom iterator implementation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;They are a powerful, versatile feature of JavaScript, although they are not commonly used. In this article, we got a brief overview of what are iterators and generators, what are generator functions, why we need to use generators, and finally how to work with generators and generator functions. We also discussed a very powerful use case of generators for dealing with infinite data streams.&lt;/p&gt;

&lt;p&gt;That's it from me folks, thank you so much for reading this blog! 🙌 I hope I was able to make generators interesting for you and was able to give a brief overview of them through this blog 😄&lt;/p&gt;

&lt;p&gt;Last but not the least, &lt;a href="https://i.giphy.com/media/tEaDT85En43i8/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/tEaDT85En43i8/giphy.gif" alt="You folks are awesome!" width="300" height="215"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Feel free to reach out to me:&lt;br&gt;
&lt;a href="https://twitter.com/DevanshYtweets"&gt;Twitter&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.linkedin.com/in/devansu-yadav/"&gt;Linkedin&lt;/a&gt;&lt;br&gt;
&lt;a href="https://github.com/Devansu-Yadav"&gt;GitHub&lt;/a&gt;&lt;br&gt;
You can also reach out to me over mail: &lt;a href="//mailto:devansuyadav@gmail.com"&gt;devansuyadav@gmail.com&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

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