<?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: Prince Sumberia</title>
    <description>The latest articles on DEV Community by Prince Sumberia (@princesumberia7).</description>
    <link>https://dev.to/princesumberia7</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%2F333411%2Fd5ac0993-700c-44fd-83de-3f9478940945.jpg</url>
      <title>DEV Community: Prince Sumberia</title>
      <link>https://dev.to/princesumberia7</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/princesumberia7"/>
    <language>en</language>
    <item>
      <title>Understanding Closures in Javascript</title>
      <dc:creator>Prince Sumberia</dc:creator>
      <pubDate>Wed, 17 Feb 2021 10:46:26 +0000</pubDate>
      <link>https://dev.to/princesumberia7/understanding-closures-in-javascript-1m0</link>
      <guid>https://dev.to/princesumberia7/understanding-closures-in-javascript-1m0</guid>
      <description>&lt;p&gt;The closure is one of the most important and elegant concepts of JS. It forms the most fundamental concept of many important functions and concepts in JS. It is a powerful concept that allows us to create many useful and powerful pro-level functions like &lt;code&gt;once&lt;/code&gt; and &lt;code&gt;memoize&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Many JavaScript &lt;code&gt;design patterns&lt;/code&gt; including the &lt;code&gt;module pattern&lt;/code&gt; use closure. Moreover, Closure allows us to &lt;code&gt;build iterators&lt;/code&gt;, handle the &lt;code&gt;partial application&lt;/code&gt;, and &lt;code&gt;maintain state&lt;/code&gt; in an asynchronous world.&lt;/p&gt;

&lt;p&gt;Before understanding and getting in-depth into the closure please keep in mind that whenever a function runs or invoked then it gets a new execution context with local memory. When a function gets called then the function is pushed onto the call stack. When the function starts executing we create a live store of data that can be called &lt;code&gt;local memory&lt;/code&gt;, &lt;code&gt;variable environment&lt;/code&gt;, or &lt;code&gt;state&lt;/code&gt;. When the function finishes executing, the result is returned and execution context with its local memory is deleted and the function is popped off the call stack.&lt;/p&gt;

&lt;p&gt;But with closures, we can create functions with memories. The closure is just a function that returns another function. The following is an example of closures.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;createFunction&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;multiplyBy2&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;num&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt; &lt;span class="err"&gt; &lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;num&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;multiplyBy2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;generatedFunc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;createFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;generatedFunc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, look at the following function without actually running it in the console. Go through the function theoretically and try to predict the result keeping in mind our current understanding and discussion so far.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;outer&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt; &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;counter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;incrementCounter&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 
&lt;span class="err"&gt; &lt;/span&gt; &lt;span class="err"&gt; &lt;/span&gt; &lt;span class="nx"&gt;counter&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
&lt;span class="err"&gt; &lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;incrementCounter&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myNewFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;outer&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;myNewFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;myNewFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The execution will take as follows:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First of all we are declaring a function named &lt;code&gt;outer&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Now we are declaring a const &lt;code&gt;myNewFunction&lt;/code&gt; which is uninitialized.&lt;/li&gt;
&lt;li&gt;Then we are calling the &lt;code&gt;outer&lt;/code&gt; function and it is put on the call stack. Now it will create a new execution context with the local variable environment.&lt;/li&gt;
&lt;li&gt;Inside the &lt;code&gt;outer&lt;/code&gt; function, first, we declare a variable counter to 0. And we are defining a function &lt;code&gt;incrementCounter&lt;/code&gt; and lastly returning the function &lt;code&gt;incrementCounter&lt;/code&gt;. Now the outer is popped off the calls stack and its execution context gets deleted.&lt;/li&gt;
&lt;li&gt;Now the const &lt;code&gt;myNewFunction&lt;/code&gt; gets initialized with the returned value of the &lt;code&gt;outer&lt;/code&gt; i.e function definition of &lt;code&gt;incrementCounter&lt;/code&gt;. Now the &lt;code&gt;myNewFunction&lt;/code&gt; will be like.
&lt;code&gt;function myNewFunction (){ counter ++; }&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Now we are calling &lt;code&gt;myNewFunction&lt;/code&gt;. It will be added to the call stack.&lt;/li&gt;
&lt;li&gt;This will create a brand new execution context and Local environment variable.&lt;/li&gt;
&lt;li&gt;In the function definition, we can see the counter is incremented but the counter variable is not declared or initialized.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now theoretically this should result in an &lt;code&gt;error&lt;/code&gt; the counter is not declared or initialized.&lt;/p&gt;

&lt;p&gt;Now try to run it in the console, you will notice that it will not result in an error but something strange happens. The result will be:- &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;2&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Lexical scope:&lt;/strong&gt; One intricacy of JavaScript is how it looks for variables. If it can’t find a variable in its local execution context, it will look for it in its &lt;code&gt;calling context&lt;/code&gt;. And if it doesn't found there, it will keep looking, until it reaches the &lt;code&gt;global execution context&lt;/code&gt;. And if it does not find it there, it’s undefined.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;But how this can be possible ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Answer is..... &lt;strong&gt;THE BACKPACK&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Back Pack
&lt;/h2&gt;

&lt;p&gt;The concept of the backpack was introduced to me by Will Sentance while I was going through Javascript the hard parts course. No doubt one of the best online courses taught by certainly the best instructor I ever had with excellent teaching skills.&lt;/p&gt;

&lt;p&gt;Now let us go back to the previous code and at the instance when the &lt;code&gt;incrementCounter&lt;/code&gt; is returned to the const &lt;code&gt;myNewFunction&lt;/code&gt; (Line Number: 5).  Whats happens at that stage is that &lt;code&gt;myNewFunction&lt;/code&gt; somehow maintains the bond to &lt;code&gt;outer&lt;/code&gt; function local memory i.e, the local memory of the &lt;code&gt;outer&lt;/code&gt; function gets &lt;strong&gt;&lt;em&gt;returned out&lt;/em&gt;&lt;/strong&gt; and attached on the back of &lt;code&gt;incrementCounter’s&lt;/code&gt; function definition. So &lt;code&gt;outer’s&lt;/code&gt; local memory is now stored and attached to &lt;code&gt;myNewFunction&lt;/code&gt; - even though the &lt;code&gt;outer’s&lt;/code&gt; execution context is long gone.  When we run &lt;code&gt;myNewFunction&lt;/code&gt; globally, it will first look in its own local memory (as we’d expect), but then in &lt;code&gt;myNewFunction’s&lt;/code&gt; &lt;strong&gt;backpack.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What makes them so special that the function return will have a special hidden &lt;code&gt;[[scope]]&lt;/code&gt; property attached with it which can be called a backpack for better understanding. That contains a reference to all the variables in the local memory of the main function that returned that function. And this way we can have a function that has access to the local memory of the main function even after it has been executed i.e even after its execution context is deleted. The closure gives our functions persistent memory.&lt;/p&gt;

&lt;p&gt;The different name of the backpack&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Closed over ‘Variable Environment’ (C.O.V.E.)&lt;/li&gt;
&lt;li&gt;Persistent Lexical Scope Referenced Data (P.L.S.R.D.)&lt;/li&gt;
&lt;li&gt;Backpack&lt;/li&gt;
&lt;li&gt;Closure - Official
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;outer&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;counter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;incrementCounter&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt; &lt;span class="err"&gt; &lt;/span&gt;&lt;span class="nx"&gt;counter&lt;/span&gt; &lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;incrementCounter&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myNewFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;outer&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;myNewFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// 1&lt;/span&gt;
&lt;span class="nx"&gt;myNewFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// 2&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;anotherFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;outer&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;anotherFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// 1&lt;/span&gt;
&lt;span class="nx"&gt;anotherFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// 2&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We call the &lt;code&gt;outer()&lt;/code&gt; function and store the returned value with the backpack in const &lt;code&gt;myNewFunction&lt;/code&gt;. The &lt;code&gt;myNewFunction&lt;/code&gt; will have access to all the &lt;code&gt;[[scope]]&lt;/code&gt; property containing the live data of &lt;code&gt;outer&lt;/code&gt; in the backpack or closure. Now the myNewFunction will have a definition of &lt;code&gt;incrementCounter&lt;/code&gt; and will be something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;myNewFunction&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt; &lt;span class="nx"&gt;counter&lt;/span&gt; &lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="err"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As soon as we call &lt;code&gt;myNewFunction&lt;/code&gt; for the first time, a brand new execution context is created and put on top of the call stack. Now it will look for the counter variable in its &lt;strong&gt;local environment&lt;/strong&gt;, and it will not find it there. And then it will look for it in the &lt;strong&gt;backpack&lt;/strong&gt; and will find it there will the value of 0. And then increment it and return it and the function is popped off the call stack.  &lt;/p&gt;

&lt;p&gt;Now we are again calling &lt;code&gt;myNewFunction&lt;/code&gt; and now again brand new execution context is created and put on top of the call stack. Now again it will find the counter in the &lt;strong&gt;backpack&lt;/strong&gt; and not in the local memory.&lt;/p&gt;

&lt;p&gt;But this time the value of the counter is 1 as set by the previous &lt;code&gt;myNewFunction&lt;/code&gt; call as the backpack is still the same as we are instance of &lt;code&gt;outer()&lt;/code&gt; is the same. It will increment it to 2 and return it and the function is popped off the call stack.&lt;/p&gt;

&lt;p&gt;If we run &lt;code&gt;outer&lt;/code&gt; again and store the returned &lt;code&gt;incrementCounter&lt;/code&gt; function definition in &lt;code&gt;anotherFunction&lt;/code&gt;, this new &lt;code&gt;incrementCounter&lt;/code&gt; function was created in a new execution context and therefore has a brand &lt;strong&gt;new independent backpack&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Every instance of the &lt;code&gt;outer&lt;/code&gt; function being executed create a brand new backpack or closure.&lt;/p&gt;

&lt;h2&gt;
  
  
  Uses of Closures
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Gives our functions persistent memory.&lt;/li&gt;
&lt;li&gt;Helper functions: Everyday professional helper functions like ‘once’ and ‘memoize’&lt;/li&gt;
&lt;li&gt;Iterators and generators: Which use lexical scoping and closure to achieve the
most contemporary patterns for handling data in JavaScript&lt;/li&gt;
&lt;li&gt;Module pattern: Preserve state for the life of an application without polluting the
global namespace&lt;/li&gt;
&lt;li&gt;Asynchronous JavaScript: Callbacks and Promises rely on the closure to persist state
in an asynchronous environment&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That's all! If you have any suggestions or find any errors in the article please let me know in the comment section. If you enjoyed the article please share it on social media platforms.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>functional</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
