<?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: Piyush Sharma</title>
    <description>The latest articles on DEV Community by Piyush Sharma (@piyusharmap).</description>
    <link>https://dev.to/piyusharmap</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%2F1147564%2Fc773fb84-1d70-4b60-8be3-65557eae8774.jpeg</url>
      <title>DEV Community: Piyush Sharma</title>
      <link>https://dev.to/piyusharmap</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/piyusharmap"/>
    <language>en</language>
    <item>
      <title>Let's understand what JavaScript Closures are.</title>
      <dc:creator>Piyush Sharma</dc:creator>
      <pubDate>Fri, 27 Oct 2023 18:04:23 +0000</pubDate>
      <link>https://dev.to/piyusharmap/lets-understand-what-javascript-closures-are-510o</link>
      <guid>https://dev.to/piyusharmap/lets-understand-what-javascript-closures-are-510o</guid>
      <description>&lt;p&gt;If you are learning JavaScript, there is no chance that you haven't heard about closures. Closures are one of the most important topics that also help you master other advanced topics. In the beginning, they may seem very overwhelming, but once you understand them, they become quite easy.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are closures, anyway? 🤔
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Closures refer to functions that are bundled (enclosed) together with their parent's lexical scope and have access to that parent's lexical scope even after the parent function has executed. In other words, even after the parent function goes out of execution, the closure can still access the variables and methods defined inside it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's understand this using an example. Suppose we have a variable, say, &lt;em&gt;globalVariable&lt;/em&gt;, in the global scope, and an outer function which has another variable, &lt;em&gt;localVariable&lt;/em&gt;, inside it. Now, the &lt;em&gt;localVariable&lt;/em&gt; can only be accessed inside the outer function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let globalVariable = 43; // can be accessed anywhere in the code

const outerFunction = () =&amp;gt; {
    let localVariable = 27; // can be accessed only inside outerFunction()
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's suppose we have an inner function inside the outer function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let globalVariable = 43;

const outerFunction = () =&amp;gt; {
    let localVariable = 27;
    function innerFunction(){}
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point of time the inner function has access to both &lt;em&gt;localVariable&lt;/em&gt; and &lt;em&gt;globalVariable&lt;/em&gt;, why? Because innerFunction() has access to its parent's lexical environment.&lt;/p&gt;

&lt;p&gt;Lexical Environment of outerFunction()&lt;br&gt;
 -&amp;gt; &lt;em&gt;globalVariable&lt;/em&gt;&lt;br&gt;
 -&amp;gt; &lt;em&gt;localVariable&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now if we try to log the values of &lt;em&gt;globalVariable&lt;/em&gt; and &lt;em&gt;localVariable&lt;/em&gt; in the console we will get 43 and 27.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let globalVariable = 43;

const outerFunction = () =&amp;gt; {
    let localVariable = 27;
    function innerFunction(){
        console.log(`Inner -&amp;gt; Global Variable: ${(globalVariable)}`);
        console.log(`Inner -&amp;gt; Local Variable: ${(localVariable)}`);
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Till now, everything is pretty simple, right? So, what exactly is a closure here?&lt;/p&gt;

&lt;p&gt;In this example, the innerFunction() has a closure over its parent's lexical environment.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Every time a function is created, a closure is also created along with it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, if we return this innerFunction() and assign it to some other variable, we can still access the &lt;em&gt;localVariable&lt;/em&gt; outside the outerFunction().&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let globalVariable = 43;

const outerFunction = () =&amp;gt; {
    let localVariable = 27;
    return function innerFunction(){
        console.log(`Inner -&amp;gt; Global Variable: ${(globalVariable)}`);
        console.log(`Inner -&amp;gt; Local Variable: ${(localVariable)}`);
    }
};

const result = outerFunction(); // this will contain the inner function 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now also modify the local variable through the closure, 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 innerFunction = () =&amp;gt; {
        console.log(`Inner -&amp;gt; Global Variable: ${(globalVariable += 1)}`);
        console.log(`Inner -&amp;gt; Local Variable: ${(localVariable += 1)}`);
    };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Closures using IIFE (Immediately Invoked Function Expression)&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 playGame = (() =&amp;gt; {
    let tokenCounter = 5;

    console.log(`Start Game. Tokens available: ${tokenCounter}`);

    return function () {
        if (tokenCounter === 0) {
            console.log(`No more tokens available.`);
        } else {
            console.log(`Token(s) available: ${(tokenCounter -= 1)}`);
        }
    };
})();

playGame();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the playGame() function has a closure over the variable tokenCounter, enabling it to modify the value of tokenCounter, which cannot be accessed otherwise.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Applications of closures&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Data encapsulation&lt;/li&gt;
&lt;li&gt;Event handlers&lt;/li&gt;
&lt;li&gt;Callbacks&lt;/li&gt;
&lt;li&gt;Currying&lt;/li&gt;
&lt;li&gt;and many more..&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Well, there is much more to discuss about closures, which I will try to cover in another post. Try to go over the examples again and read the official documentation to gain a solid grasp of closures.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures"&gt;MDN Docs for Closures&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Happy Coding💻&lt;/p&gt;

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