<?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>Forem: Ashwanth A R</title>
    <description>The latest articles on Forem by Ashwanth A R (@ashwanth1109).</description>
    <link>https://forem.com/ashwanth1109</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%2F175593%2Fc65740ea-7728-4057-8f9e-754ee7482f5a.png</url>
      <title>Forem: Ashwanth A R</title>
      <link>https://forem.com/ashwanth1109</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ashwanth1109"/>
    <language>en</language>
    <item>
      <title>Demystifying JavaScript Closures</title>
      <dc:creator>Ashwanth A R</dc:creator>
      <pubDate>Sun, 27 Sep 2020 19:15:41 +0000</pubDate>
      <link>https://forem.com/ashwanth1109/demystifying-javascript-closures-4e3i</link>
      <guid>https://forem.com/ashwanth1109/demystifying-javascript-closures-4e3i</guid>
      <description>&lt;p&gt;For a long time, I've perceived closures as this arcane topic that had a tendency to unnerve me. However, it is a powerful feature of JavaScript that lets you do some neat stuff. In this article, I will cover its basics and we will look at one practical usage, and hopefully you will find it intelligible as well (if you don't already).&lt;/p&gt;

&lt;h1&gt;
  
  
  The core of JavaScript
&lt;/h1&gt;

&lt;p&gt;JavaScript is a single-threaded language. This means that it can only run/execute one piece of code at a time and must finish it, before executing the next bit. In layman's terms, it cannot multi-task. In more technical terms, it has,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One Thread of Execution&lt;/li&gt;
&lt;li&gt;One Memory Heap&lt;/li&gt;
&lt;li&gt;One Call Stack&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;strong&gt;thread of execution&lt;/strong&gt; basically refers to JavaScript's thread, going line by line over your code and executing each line. There is a caveat to this however. If a function is encountered, JavaScript will declare the function in memory and move to the next line after the function. It will not go into the body of the function until a function call is encountered. Once the function completes, it will then jump back (return) to the line that initially called the function.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bAqSsU8---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/kzbawqhavtrcrf4vmhvf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bAqSsU8---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/kzbawqhavtrcrf4vmhvf.png" alt="Thread of execution"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Before your code starts to run, a global execution context is created with a memory heap. &lt;em&gt;An execution context is the environment in which your thread of execution runs.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Every time your thread of execution enters an execution context, this context is pushed onto your call stack. Therefore when your code starts to run initially, global context is pushed onto the call stack and the JavaScript compiler encounters LINE 1.&lt;/p&gt;

&lt;p&gt;It takes the entire function definition (along with the code) and stores it in the &lt;strong&gt;memory heap&lt;/strong&gt;. It does not run any of the code inside the function.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--46LGlWZT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/b90rf5jjarsb6tzwhtsm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--46LGlWZT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/b90rf5jjarsb6tzwhtsm.png" alt="Call Stack and Memory Heap"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The next line in the order of execution is LINE 6, where the function is called (or invoked). When a function is called, a new execution context is created and pushed onto the stack. It is at this point, that JavaScript enters inside the function to execute the function body (LINE 2).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oUA5VhEu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/u9ypmb24y0f2l59utmwe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oUA5VhEu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/u9ypmb24y0f2l59utmwe.png" alt="Function call"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It is also interesting to note that LINE 6 has not completed its execution though (result is still uninitialized), it is now waiting for the function to complete its execution at which point the &lt;code&gt;addOne()&lt;/code&gt; context is popped off the stack and destroyed. Before destruction however, it will return the calculated value back to LINE 6 and initialize the value of result.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--47-tWbpC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/1f30859d8hnoar0zopar.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--47-tWbpC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/1f30859d8hnoar0zopar.png" alt="Final State"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Where do closures come into the picture?
&lt;/h1&gt;

&lt;p&gt;Now, I mentioned in the previous paragraph that the execution context of &lt;code&gt;addOne()&lt;/code&gt; is destroyed after the function has completed its execution. So there is no label called "val" in our memory with a value initialized to it anymore. Its all been completely removed from memory.&lt;/p&gt;

&lt;p&gt;This behavior is a good thing, because each time we run our function with different arguments, we don't typically need to know what values the function was previously run with or what intermediate values were generated during execution. But, there are some cases where having memory attached to our function definition that persists across execution will prove to be a powerful capability that lets us do incredible things.&lt;/p&gt;

&lt;h1&gt;
  
  
  Attaching memory to function
&lt;/h1&gt;

&lt;p&gt;Let's look at some code,&lt;br&gt;
&lt;/p&gt;

&lt;div class="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;createAddFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;addByN&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;val&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;val&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;addByN&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;addBy10&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;createAddFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;addBy10&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here we have a function, &lt;code&gt;createAddFunction&lt;/code&gt; which takes a parameter &lt;code&gt;n&lt;/code&gt; and returns a function called &lt;code&gt;addByN&lt;/code&gt;. Let's break this down. When the compiler starts, it creates a global context, and encounters LINE 1 where it defines a label in memory (called &lt;code&gt;createAddFunction&lt;/code&gt;) and stores the entire function definition under this label.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bek9LSeg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/r2bbbsatb958pdsxlgv4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bek9LSeg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/r2bbbsatb958pdsxlgv4.png" alt="createAddFunction defined"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, it creates a label in memory called &lt;code&gt;addBy10&lt;/code&gt; which remains uninitialized till the function call &lt;code&gt;createAddFunction()&lt;/code&gt; finishes execution and returns. When this function gets executed, it creates a new execution context and pushes this on to the stack. Since we pass the value &lt;code&gt;n&lt;/code&gt; as 10, this gets stored in the &lt;code&gt;createAddFunction&lt;/code&gt; context. In the function body, it also defines &lt;code&gt;addByN&lt;/code&gt; function to be stored in memory.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mwphljXv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/4e0q1kklxssiaio89x1g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mwphljXv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/4e0q1kklxssiaio89x1g.png" alt="createAddFunction execution"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then it returns this function &lt;code&gt;addByN&lt;/code&gt; to be stored as initial value for &lt;code&gt;addBy10&lt;/code&gt; label in memory. Once the value has been returned, the &lt;code&gt;createAddFunction&lt;/code&gt; execution context is popped off the call stack and destroyed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--btFYdwSt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/uo4p9qjh8ciu1pcqxcps.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--btFYdwSt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/uo4p9qjh8ciu1pcqxcps.png" alt="createAddFunction complete"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We then invoke the function &lt;code&gt;addBy10(2)&lt;/code&gt; with an argument &lt;code&gt;2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OpvaIbwK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/061unjliklurkixn73tv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OpvaIbwK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/061unjliklurkixn73tv.png" alt="addBy10 definition"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our &lt;code&gt;addBy10&lt;/code&gt; function would be defined as above. Its the same as our &lt;code&gt;addByN&lt;/code&gt; function except it is now stored under a different label in memory. Here comes the kicker. The parameter &lt;code&gt;val&lt;/code&gt; takes on the value 2, but what is the value of &lt;code&gt;n&lt;/code&gt; ? Its not defined inside our function, nor is it defined in our global execution context. Furthermore, there are no other execution contexts left because &lt;code&gt;createAddFunction&lt;/code&gt; context was destroyed. At this point, we would expect &lt;code&gt;n&lt;/code&gt; to be undefined, but its not. Thanks to how JavaScript behaves in these circumstances because of closures. Our function somehow remembers that the value of &lt;code&gt;n&lt;/code&gt; at the time of function creation was &lt;code&gt;10&lt;/code&gt; and thus we can say, our function has persistent memory.&lt;/p&gt;

&lt;h1&gt;
  
  
  Lexical Scoping and Closures
&lt;/h1&gt;

&lt;p&gt;Scope is the set of rules in a programming language that dictates what data is available to the compiler within a particular execution context. JavaScript has the scope rule of Lexical / Static Scoping. Lexical Scoping is a description of how the JavaScript compiler resolves variables names when you have functions nested. That is, the parent of a function determines what data that function has access to (in addition to the data that is local to the function).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hSPFaslX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/ryb65wc33adb5vniaw1i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hSPFaslX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/ryb65wc33adb5vniaw1i.png" alt="Lexical Scoping"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When the thread of execution is inside the inner execution context, it has access to variables defined in the outer execution context via our scoping rule.&lt;/p&gt;

&lt;p&gt;So, when the &lt;code&gt;addByN&lt;/code&gt; function is returned from the &lt;code&gt;createAddFunction&lt;/code&gt; execution context, it takes along with it all the variables that it has access to. Because of lexical scoping, this includes the key-value pair of &lt;code&gt;n&lt;/code&gt; and &lt;code&gt;10&lt;/code&gt;. This is called a closure. &lt;em&gt;A closure is the combination of a function and the lexical environment within which that function was declared&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NWq7LV9a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/l3hfkfeh0gxk9vcthpn2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NWq7LV9a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/l3hfkfeh0gxk9vcthpn2.png" alt="Closure"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, our label &lt;code&gt;addBy10&lt;/code&gt; is not merely a reference to a function anymore, but a reference to a function and a data store (that persists before, during and after the function call). &lt;/p&gt;

&lt;p&gt;It is important to note that this value of &lt;code&gt;n = 10&lt;/code&gt; cannot be accessed in any other way but by calling the function and this usage depends on how the function was originally defined. Hence, it is protected persistent data.&lt;/p&gt;

&lt;h1&gt;
  
  
  Iterators using closures
&lt;/h1&gt;

&lt;p&gt;A good example for closures is iterators in JavaScript. An iterator is an object which defines a sequence of values that can be accessed by having a &lt;code&gt;next()&lt;/code&gt; method which returns an object with two properties: &lt;code&gt;value&lt;/code&gt; (next value in the sequence) and &lt;code&gt;done&lt;/code&gt; (boolean to track whether sequence has already been iterated over).&lt;/p&gt;

&lt;p&gt;If we try to implement a simple iterator, we can see the usage of closures.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;makeIterator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;currentIndex&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="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;next&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;currentIndex&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nx"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;length&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;currentIndex&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
          &lt;span class="na"&gt;done&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;};&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;

      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;currentIndex&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="na"&gt;done&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;};&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The makeIterator function creates/makes an iterator object and returns it. This can be used as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;iterator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;makeIterator&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&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;span class="kd"&gt;let&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;iterator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;done&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;RESULT&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&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;iterator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We had to use a closure in this case because we needed to store (in memory) and track the currentIndex across the &lt;code&gt;next()&lt;/code&gt; function calls as we consume our iterator.&lt;/p&gt;

&lt;p&gt;Some other places where closures are used are in the implementation of generators, promises etc. It can also be used in functions that perform large computations to store previous computations in order to not repeat it if the same arguments are passed in (memoization). Closures provide you a powerful toolkit to writing modular optimized code. And I hope with this explanation, you are as excited about using them to write better code as I am. &lt;/p&gt;

&lt;p&gt;If you have any feedback, questions, clarifications, please drop a comment and I'm happy to engage in a discussion to improve the quality of my content. Thanks for reading.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>functional</category>
    </item>
    <item>
      <title>How to publish npm packages?</title>
      <dc:creator>Ashwanth A R</dc:creator>
      <pubDate>Sat, 07 Sep 2019 09:46:58 +0000</pubDate>
      <link>https://forem.com/ashwanth1109/how-to-publish-npm-packages-2pge</link>
      <guid>https://forem.com/ashwanth1109/how-to-publish-npm-packages-2pge</guid>
      <description>&lt;p&gt;Publishing an npm package, it turns out, is not as difficult as one assumes it to be. This article will walk you through the process I followed when publishing a recent package of mine called &lt;code&gt;react-client-dimensions&lt;/code&gt;. I chose to write the article with a very specific example rather than a general mock example since I find such articles more valuable, albeit the scope it covers is limited.&lt;/p&gt;

&lt;h1&gt;
  
  
  What is the package?
&lt;/h1&gt;

&lt;p&gt;Before I walk through the steps of publishing an npm package, let me first tell you about the package. In several of my hobby projects (mostly react), I need to render a different component based on the window (or client or viewport, whatever you want to call it) size. This makes it easier to handle specific requirements for a responsive layout where media queries are not as straightforward. So I wrote a custom hook that tells me what the client dimensions are, i.e. the width and height. I was using this hook across several projects, so I decided to publish it as an npm package. Now I can use it by just installing a dependancy rather than copy-pasting my code every time.&lt;/p&gt;

&lt;h1&gt;
  
  
  Initial Setup: Got node? Okay, create directory.
&lt;/h1&gt;

&lt;p&gt;Make sure you have node installed on your machine. A node installation will also give you npm out-of-the-box which is more than sufficient but I prefer to use yarn (which is what this article will use). Take your pick, they are substitutable with each other. You can install node from &lt;a href="https://nodejs.org/en/download/" rel="noopener noreferrer"&gt;here&lt;/a&gt; and yarn from &lt;a href="https://yarnpkg.com/en/docs/install" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The first step is to create the project directory you want to publish. In my case, I create a folder called 'react-client-dimensions'.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir react-client-dimensions
cd react-client-dimensions
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  The all-important package.json
&lt;/h1&gt;

&lt;p&gt;To generate your package.json file, run yarn init command inside your project directory. The CLI wizard will guide you through a series of steps to generate your package.json configuration. Alternatively, you can use yarn init -y which has a flag to quickly set you up with a default configuration.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2APwMz50068y-1iSigFLv7-g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2APwMz50068y-1iSigFLv7-g.png" alt="package.json"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is all that we need to publish the package. I prefer to publish the package at this point so that I can change the name if it's not available. I had initially tried the name react-window-size but it was already taken, so I settled for &lt;code&gt;react-client-dimensions&lt;/code&gt;. To publish, you need an npm account. In your command line, authorize your login credentials using the command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm login
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before publishing, it is a good idea to add a license, changelog, and a readme file. NPM will always automatically include your &lt;code&gt;package.json&lt;/code&gt;, readme, changelog and license no matter what.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;touch README.md CHANGELOG.md LICENSE

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

&lt;/div&gt;



&lt;p&gt;I usually use the MIT license which can be found &lt;a href="https://opensource.org/licenses/MIT" rel="noopener noreferrer"&gt;here&lt;/a&gt;. My changelog file is typically in the following pattern.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AL4AYZn2Z8ytLGJHu9rdSCQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AL4AYZn2Z8ytLGJHu9rdSCQ.png" alt="CHANGELOG.md"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To publish our package to the registry run,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm publish
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Writing the source code
&lt;/h1&gt;

&lt;p&gt;Now we write the actual package. The meat and potatoes of what we want to achieve with the package. Typically source code is written in a directory called &lt;code&gt;src&lt;/code&gt; which separates it from the rest of our codebase. This also makes it easier to bundle all your code into a lib or dist folder after you've pre-processed your code for production use using tools such as Babel or Webpack.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AlN32-bVpRv9ofKN0sGHnlA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AlN32-bVpRv9ofKN0sGHnlA.png" alt="Source Code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There we have it. Our source code for the package. We're almost ready to publish it but not quite yet.&lt;/p&gt;

&lt;h1&gt;
  
  
  Transpiling our code with Babel
&lt;/h1&gt;

&lt;p&gt;The code we have written uses ES6+ syntax which is not supported in older browser versions. For example, arrow functions is an ES6 feature and you can see the status of support here. In order to make our code work across all environments, we use a compiler (called Babel) to compile our code and package it.&lt;/p&gt;

&lt;p&gt;We install the dependencies (as dev dependencies) for Babel using the following command. These are dev dependencies because our packaged code does not depend on.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add -D @babel/cli @babel/core @babel/preset-env
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Babel is a JavaScript compiler that converts ES6+ code into a backward-compatible version of JavaScript in old browsers or environments. The Babel CLI (&lt;a class="mentioned-user" href="https://dev.to/babel"&gt;@babel&lt;/a&gt;/cli) is a command-line tool that provides your command line with the ability to run the babel-core API (&lt;a class="mentioned-user" href="https://dev.to/babel"&gt;@babel&lt;/a&gt;/core) on your source code.&lt;/p&gt;

&lt;p&gt;With just these tools you will find that there is a lot more work that you need to do in order to micromanage the syntax transforms that are needed by your target environment. To simplify this, we add a preset (&lt;a class="mentioned-user" href="https://dev.to/babel"&gt;@babel&lt;/a&gt;/preset-env) which does this work for you in a concise manner.&lt;/p&gt;

&lt;p&gt;Now we need to tell our babel configuration to use the preset-env that we installed. We can do this by adding our babel config to our package.json file. We edit our &lt;code&gt;package.json&lt;/code&gt; file to look something like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AQFT4c4lWubFi83yeldJObw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F1%2AQFT4c4lWubFi83yeldJObw.png" alt="Updated package.json"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The important changes you need to note here are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Update main entry point to "lib/index.js" because that is where we ask babel to store our production-ready source code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We added our &lt;a class="mentioned-user" href="https://dev.to/babel"&gt;@babel&lt;/a&gt;/preset-env preset to our babel config.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We added a "build" script which uses Babel CLI to transpile our code and put it inside the lib folder. You can run it using the command: yarn build.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Every time we publish we need to run the build command first. We can automate this step by adding a "prepare" script which npm automatically runs when you run: &lt;code&gt;npm publish&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We want npm to only publish our lib folder. So we include it in the files attribute.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In this case, we tell npm to publish our package only with certain files and folders (whitelist). Alternatively, you can choose to tell npm to avoid certain files and folders (blacklist) using the &lt;code&gt;.npmignore file&lt;/code&gt;. However, I find blacklisting a more troublesome option than whitelisting. You can read more about these options &lt;a href="https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package" rel="noopener noreferrer"&gt;here&lt;/a&gt; and &lt;a href="https://medium.com/@jdxcode/for-the-love-of-god-dont-use-npmignore-f93c08909d8d" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Semantic Versioning
&lt;/h1&gt;

&lt;p&gt;The source code we added is a new version for our package. NPM won't let you publish this version without updating the version attribute of your 1package.json` file. To do this, we follow a versioning system called Semantic Versioning. You can read more about this &lt;a href="https://medium.com/@jameshamann/a-brief-guide-to-semantic-versioning-c6055d87c90e" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We want to patch update our version. So we run &lt;code&gt;npm version patch&lt;/code&gt; to update our version.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
npm version patch -m "Added source code for useClientDimensions() hook"&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once our versioning is done, we are ready to publish our package. Simply run &lt;code&gt;npm publish&lt;/code&gt; and you are done. Your package is out there now. :)&lt;/p&gt;

&lt;p&gt;Check out my package &lt;code&gt;react-client-dimensions&lt;/code&gt; here. Tell people about it if you find it useful.&lt;/p&gt;

&lt;p&gt;Thanks for reading. Drop me a comment if you have feedback/suggestions. I highly appreciate those.&lt;/p&gt;

&lt;p&gt;Have a good day.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>npm</category>
      <category>babel</category>
    </item>
  </channel>
</rss>
