<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prameet Chakraborty on Medium]]></title>
        <description><![CDATA[Stories by Prameet Chakraborty on Medium]]></description>
        <link>https://medium.com/@prameet_9116?source=rss-9ca4952ef9ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f39C4D50ziqsb_0B9XP4BQ.jpeg</url>
            <title>Stories by Prameet Chakraborty on Medium</title>
            <link>https://medium.com/@prameet_9116?source=rss-9ca4952ef9ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:10:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prameet_9116/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JavaScript’s Hidden Treasures : Closures and Hoisting]]></title>
            <link>https://medium.com/geekyants-blog/javascripts-hidden-treasures-closures-and-hoisting-6d486aa125d?source=rss-9ca4952ef9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d486aa125d</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hosting]]></category>
            <dc:creator><![CDATA[Prameet Chakraborty]]></dc:creator>
            <pubDate>Tue, 29 Aug 2017 06:00:13 GMT</pubDate>
            <atom:updated>2017-08-29T10:23:35.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*c17mFoyQ76qOMUMyUvtpYw.png" /></figure><blockquote>JavaScript possesses many advanced features that can often make us feel confused and bewildered. Let’s demystify two of them.</blockquote><h3>Closures</h3><p>We encounter closures several times while coding in JavaScript. So it’s quite necessary to understand what they actually signify. Let’s first zip through some formal definitions.</p><h4>What is a closure?</h4><blockquote>A closure is a function that has access to the parent scope, even after the scope has closed.</blockquote><p>or we can also define it as:</p><blockquote>A closure is the combination of a function and the lexical environment within which that function was declared.</blockquote><h4>Scope</h4><p><em>The Scope is essentially the lifespan of a variable in JavaScript</em>. Where<em> </em>a variable is defined plays a large role in how long that variable is around, and which functions in your program have access to it.</p><p>So it would be safe to say that any function can be considered a closure because a function can refer to or have access to:</p><ul><li>Any variable or parameter in its own function scope.</li><li>Any variable or parameters of its outer (parent) functions.</li><li>Any variable from the global scope.</li></ul><p>Let’s split the definition of Closure into three points:</p><ol><li><em>We</em> <em>can refer to variables defined outside of the current function.</em></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0c11ffffebe4ef48d76d9cd335ba8dc/href">https://medium.com/media/f0c11ffffebe4ef48d76d9cd335ba8dc/href</a></iframe><p>Here, the printData() function refers to the type variable and the modelparameter of the enclosing function setData(). So when setData() is called, printData()uses the variables and parameters of the former to print the output “Audi is a Car”.</p><p>2. <em>Inner functions can refer to variables defined in outer functions even after the latter have returned.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cbf37f2263585c366c9954cf5c6ac46/href">https://medium.com/media/0cbf37f2263585c366c9954cf5c6ac46/href</a></iframe><p>The above code may seem similar to the one in the first point. But hereprintData() is returned inside the outer setData() function, instead of being immediately called. So, the value of currentData is the inner printData() function.</p><p>3. <em>Inner functions store their outer function’s variables by reference, not by value.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fd1b27bff8466eb5bf46f175e7eeb5a/href">https://medium.com/media/1fd1b27bff8466eb5bf46f175e7eeb5a/href</a></iframe><p>Here, carData() returns an object containing two closures,get() and set(), and they both refer to the outer variable Car. While get()obtains the current value of Car, set()updates it. When myCar.get() is called for the second time, it prints the updated value of Car – “Mercedes” – rather than the previous value “Audi”.</p><p>Closures have another very interesting feature which is that the variables in a closure are automatically hidden. Closures store data in their enclosed variables without providing direct access to them. The only way to alter those variables is by providing access to them indirectly. For example, in the last code snippet, we saw that we can modify the variable Car only obliquely by using the get() and set() closures.</p><h4>Loops!</h4><p>Looping is something that tends to take a toll on everyone. When loops are not written correctly, we are left with weird outputs. Let’s look at one such example where a loop produces a confusing result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcec0ca688e00e15ab0f3f7a9f1cc368/href">https://medium.com/media/fcec0ca688e00e15ab0f3f7a9f1cc368/href</a></iframe><p>Running the above code snippet should give us the output as:</p><p>0 1 2</p><p>But instead our output will be:</p><p>3 3 3</p><p>JavaScript is single-threaded so it keeps an event queue where it queues up things to do. The closure created in each loop iteration is queued to run as soon as the rest of the current execution context finishes and CPU time is returned to the event loop. setTimeout here serves to simply defer the execution of each closure until after the loop finishes running. By that point, the final value of i is ‘3’.</p><p>We can use closures to overcome this problem. In the following code snippet, we make use of a closure by defining nested functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed4c2fb4179f7f4299a300533f8ca8cc/href">https://medium.com/media/ed4c2fb4179f7f4299a300533f8ca8cc/href</a></iframe><p>The above code prints the desired output, which is:</p><p>0 1 2</p><p>If you already have a loop that you don’t want to convert to use an iterator function, all you have to do is wrap your closure inside another closure in which you define new variables which capture the current value of the variables that change on each iteration.</p><p>The trick to capturing the variables is to make sure your outer closure executes immediately during the current iteration of the loop. Now the above code snippet will produce the desired result!</p><h3>Hoisting</h3><p>So what exactly is hoisting?</p><blockquote>Hoisting is employed to explain how Variables and Function declarations are ‘lifted’ to the top of a function or a global scope.</blockquote><p>A JavaScript interpreter performs many things behind the scene, and one of them is called hoisting.</p><p>The best way of thinking about the behavior of JavaScript variables is to always visualize them as consisting of two parts: a declaration and an assignment.</p><pre>var state;             // variable declaration<br>state = &quot;ready&quot;;       // variable definition (assignment)</pre><pre>var state = &quot;ready&quot;;   // declaration plus definition</pre><p>To understand why the concept of function declarations and definitions getting pushed to the top and assignments staying put is important, let’s consider a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34222a0193467cd74e5edbb3e2044fb5/href">https://medium.com/media/34222a0193467cd74e5edbb3e2044fb5/href</a></iframe><p>At first look, this piece of code makes no sense, for the simple reason that not only is the variable state being print even before it is declared but also the function hoisting() is being called before it is even defined. Normally <strong>Line 1</strong> should throw an error since state as it is not even declared yet.</p><p>Also, why is the statement at <strong>Line 9</strong> printing undefined even though the variable state is already declared at <strong>Line 3</strong>?</p><p>Starting from the very top, when the code is executed in JavaScript, an <em>execution context</em> is set up. There are two major types of execution contexts in JavaScript — <em>Global execution context</em> and <em>Function execution context</em>. Since JavaScript is based on a single-threaded execution model, only one piece of code can be executed at a time. For our code, the process is as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*G3_OuJ2f3813-yaMHy9LnA.png" /></figure><p>While the execution context keeps track of the execution of the code, Lexical environment keeps track of the mapping of identifiers to specific variables.</p><p>Lexical environment basically is an internal implementation of the JavaScript scoping mechanism.</p><p>Generally, the lexical environment is associated with a specific structure of the JavaScript code. For example, a function or a block of code like a forloop. Whenever a function is created, a reference to the lexical environment in which it was created is passed in an internal property named [[Environment]].</p><blockquote>So in our code example, the first time we print the value of the state, it does not throw an error because internally Javascript has already assigned an identifier to it, which is not assigned any value. So it prints <em>undefined</em></blockquote><blockquote>The second time it is called, it again prints undefined because now it is in the <em>hoisting()</em> execution context and not in the global execution context. In this context, the variable <em>state</em> is still undefined.</blockquote><p>Now let’s change our preceding code a bit. This time we print the value of the variable state before hoisting() is called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdf7517b90b3038e21a656e24ef05620/href">https://medium.com/media/fdf7517b90b3038e21a656e24ef05620/href</a></iframe><p>This time, our code prints Ready instead of undefined. As we learned in the earlier section, this happens because now we are in the global execution context and not in Hoisting’s function execution context.</p><h3>Things to remember</h3><ul><li>Both function and variable declarations are hoisted to the top of the containing scope, before any part of our code is executed.</li><li>Functions are hoisted first, and then variables.</li><li>Function declarations have priority over variable declarations, but not over variable assignments.</li></ul><h3>Conclusion</h3><p>JavaScript developers often face these issues, but fail to grasp the reason behind the unexpected behavior. Through this article, we tried to clear some of the myths and ambiguities that a developer often comes across while dealing with Closures and Hoisting.</p><h3>About The Author</h3><p>I am <a href="https://medium.com/u/9ca4952ef9ca">Prameet Chakraborty</a> and I am a software developer at <a href="https://geekyants.com/?utm_source=geekyantsblog&amp;utm_medium=article&amp;utm_campaign=blog">GeekyAnts</a>. I am most passionate about front-end and love coding in JavaScript and React.</p><p>Thanks for reading. Please 👏 if you liked this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d486aa125d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekyants-blog/javascripts-hidden-treasures-closures-and-hoisting-6d486aa125d">JavaScript’s Hidden Treasures : Closures and Hoisting</a> was originally published in <a href="https://medium.com/geekyants-blog">The GeekyAnts Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>