<?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 aiswarya krishna on Medium]]></title>
        <description><![CDATA[Stories by aiswarya krishna on Medium]]></description>
        <link>https://medium.com/@aiswaryakkrish?source=rss-e01fd3f8d1a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*KJJG-jOaU9bwZsz9RSzybw.jpeg</url>
            <title>Stories by aiswarya krishna on Medium</title>
            <link>https://medium.com/@aiswaryakkrish?source=rss-e01fd3f8d1a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:49:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aiswaryakkrish/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[Inspecting one of the most famous JavaScript bugs of all time]]></title>
            <link>https://medium.com/free-code-camp/inspecting-one-of-the-most-famous-javascript-bugs-of-all-time-61e7c27fe603?source=rss-e01fd3f8d1a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/61e7c27fe603</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[aiswarya krishna]]></dc:creator>
            <pubDate>Fri, 05 Apr 2019 17:33:35 GMT</pubDate>
            <atom:updated>2020-02-28T08:47:48.008Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inspecting one of the most famous JavaScript bugs of all time.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHU4sfE-LVZHDL0sBxJ2kA.jpeg" /></figure><p>One fine day evening, after writing a handful of beautiful JavaScript code, sipping your coffee, you smile — the code looks especially beautiful today, and you feel a sense or serenity filling your head.</p><p>Then you decide to fire up your debug console and take a look at the memory consumption, and the performance.</p><p>You take one peek at the console inspector and the sense of serenity is long gone, and something sends chills down your spine.</p><p>The trace shows a mounting slope that resembles the temperature graph of planet Earth. It’s bad. Quite bad.</p><p>You are leaking memory. And even forcing the GC to do a force sweep doesn’t do you any favors. Your once-so-beautiful code is now a tangled mess of leaky logic.</p><h4>Strictly off-topic; if you love the way I explain technology, you should definitely sign up for my newsletter singularity shots <a href="http://singularity.substack.com/">here</a>. I send small shots of wisdom every two days.</h4><p>As developers, we all have gone through this scenario before. We have coded, inspected and spent days racking our brains over leaky code.</p><p>But the below sets a new standard for leaky code. And it required a new diagnosis to isolate and fix it.</p><p>Here, I am dissecting one of the most famous JavaScript bugs of all time, and yes, it was caused by a faulty implementation of closure.</p><p>Let’s jump right in.</p><p>Imagine the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ray1C2aDxRxmBRn0lzs4Xg.png" /></figure><p>Every second, the replaceThing function will be executed. theThing variable will be replaced with a new object containing a gigantic string. Before that, the original value of theThing is saved in a local variable originalThing. After the function is returned, the old value of theThing can be garbage collected, which also happens to collect the long string inside it, because nothing refers to it anymore.</p><p>So the memory allocation is pretty straightforward: it allocates a big string at every iteration of the function, and at the same time, it deletes the previous big string. So there are no further references to originalThing and theThing, which leads to their collection.</p><p>Not a big deal huh?</p><p>But what if we had a certain specific set of needs that required us to create a closure inside replaceThing, thereby outlasting replaceThing?</p><p>Like in the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwvOoTHEHoPn_MGD9yrXhQ.png" /></figure><p>Now there is a new function “someMethod” inside theThing object. This sets up a closure scope. This is another way of saying that someMethod needs access to originalThing and theThing even after the function replaceThing has exited. I mean, that’s the entire point of closures right? So this can lead to boundless memory growth, since each iteration of the replaceThing function, creates its own version of theThing and that version would point to the previous version through originalThing.</p><p>Fortunately, most JavaScript runtimes (that run behind Chrome, Node and React) are smart enough to understand that originalThing is not actually used in the closure “someMethod”. So it is not put into someMethod’s closure scope, and is eventually GC’d when the function replaceThing exits.</p><p>Lucky for us, there is no reference ever anywhere to originalThing.</p><p>Wow. So far so good.</p><p><strong>So next level down, we bring in the big guns.</strong></p><p>What if we had a reference somewhere to originalThing, that requires the closure to hold onto originalThing?</p><p>That would make things ugly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JbXFFzVGn9xPkW8cyk4w0w.png" /></figure><p>Fire up your console and take a look.</p><p>We’re using an extra megabyte every second! So it looks like we are leaking longStr.</p><p>But nothing seems to have changed. OriginalThing is referenced in only two places. One is in the main body of the function replaceThing, and the other is inside the function unused. Both of these get cleaned up once replaceThing ends. We don’t even run the function “unused” . The only stuff that escapes the destruction of replaceThing is the closure created around “someMethod”. Surprisingly, someMethod doesn’t event refer to originalString!</p><p>This behaviour has a lot to do with the way closures are implemented in JavaScript.</p><p>In JavaScript, as we already know, every function is an object. This object has access to another object that represents its scope. So, if a function has access to three variables a, b and c, the function will have access to dictionary style object with its own scope — containing a, b and c.</p><p><strong>This dictionary styled object is the function’s lexical environment.</strong></p><p>So in our case, both the functions “unused” and “someMethod” has access to the same lexical environment (or scope). This environment is their closure scope. It is imperative that this scope is shared between all the functions that has access to it.</p><p>That means if we have three functions, sample1, sample2 and sample3, all of them are inside a main function named “mainFun”. Imagine that there is a variable a, in the main body of mainFun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*hmmsjxx3UD63CgKX7XjG_A.png" /></figure><p>The runtime needs to make sure that the three functions sample1, sample2 and sample3 need to have access to the same “a”.</p><p>This is the same thing that happens in our case with “unused” and “someMethod”. Both of them share the same lexical scope. Both of them have access to the same “originalThing”. But as we have already discussed, V8 is smart enough to keep originalThing out of lexical scope (to make them available for GC) if they are not referenced by any functions. This is why the first example doesn’t leak.</p><p>But as soon as the function “unused” references it, originalThing ends up in the lexical scope, which is not GC’d. This leads to boundless memory leak.</p><p>This bug was discovered in the Meteor framework.</p><p>How to solve this bug?</p><p>Simple!</p><p>Just add one single line:</p><pre>originalThing = null</pre><p>to the end of replaceThing. This way, after each function iteration, the name originalThing will exist in the lexical scope of someMethod, but there will not be a link to the long string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cGDmdVoITOWuiArr06Gqw.png" /></figure><p>There you go! So have a nice time until we meet again.</p><p>This is my learning blog. I write as I learn new things. This blog and codes are inspired from an Original bug discovered in the Meteor’s live HTML template rendering system. The Original blog post is <a href="https://blog.meteor.com/an-interesting-kind-of-javascript-memory-leak-8b47d2e7f156">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61e7c27fe603" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/inspecting-one-of-the-most-famous-javascript-bugs-of-all-time-61e7c27fe603">Inspecting one of the most famous JavaScript bugs of all time</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigate the deepest parts of JavaScript- Closures [3/10]]]></title>
            <link>https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-3-10-bf1974dbfaa9?source=rss-e01fd3f8d1a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf1974dbfaa9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[aiswarya krishna]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 11:01:02 GMT</pubDate>
            <atom:updated>2020-02-28T11:06:18.044Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7lNKf02GZF_G0KjSlVy8g.jpeg" /></figure><p>Note: This is my ongoing series about intricate JavaScript topics. Please read the previous articles of this series here:</p><ul><li><a href="https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-1-10-a4214680b6f5">Navigate the deepest parts of JavaScript- Closures [1/10]</a></li><li><a href="https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-2-10-b7deac267d1">Navigate the deepest parts of JavaScript- Closures [2/10].</a></li></ul><p>Now that you have made peace with what closures are and have seen an example of how they can be used to achieve certain behaviors in our code, lets dive more into how it can be used to achieve the <strong><em>module design pattern.</em></strong></p><p>Consider the following example. You are doing the navigation of a website. You are directly dealing with the DOM to swipe the current page left or right. You come up with the following code. The code is self-explanatory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQrYqPK5c9aDWE3sGmeZdA.png" /></figure><p>It has two functions, <em>forward()</em> and <em>backward()</em>. The forward function slides the page in forward direction and the backward function slides the page backwards. Before doing anything, the forward function checks if we are already on the last page. If we are, that means we don’t have anymore pages to move forward to. So the function just returns by doing nothing. Same way, the backward function checks if we are already on the first page. If we are, you know what that means.</p><p>Now, as you can see, there are many problems with the above code. For starters, let’s say that there are two <strong>global functions</strong>. You can be sure that as your code base grows, this mess will grow out leaps and bounds and you will soon lose track of what is declared in the global namespace. Just imagine, what if, in some other page, you will accidentally declare another function with the same name. Because, as the function “forward” applies to page navigation, it makes sense the same name forward() also applies to another function that moves a slider within a page, maybe? Then you will have to keep an index of all the global things; and trust me, that is not something you should do. Then you should come up with alternatives like “<em>moveForward()</em>” or “<em>next()</em>” for other functions; and in a while, your codebase becomes a garden variety. In no time, you will lose track of your code base as it grows.</p><p>What you should do is think about the person who is going to end up maintaining your code. You already know how the saying goes. “Always think that the person who ends up maintaining your code is a violent psychopath who knows where you live.”</p><p>What you need to do now is, move the two global functions from global namespace to their own object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcA6r3sPQ8N0q5M4OuVClg.png" /></figure><p>So much better. Now you can call your functions as <em>mainNavigation.forward()</em> and it really makes sense. Still, there are two global variables, currentIndex and maxIndex keeping track of the current page’s index and total page numbers. These two also “Pollute” the global namespace; because you can end up declaring other variables with the same name to keep track of something else somewhere else in your code and your code gradually becomes spaghetti. So it makes sense to do the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwYCZ22s5HArNl7RdGDGvQ.png" /></figure><h4>What you have just done is; moved all the things regarding the main navigation into it’s own function expression; in case, here it is a Immediately invoked function expression, or IEFE.</h4><p>Now they are wrapped up nicely and tightly and the variables doesn’t pollute the global namespace.</p><blockquote>But are they now wrapped up too tightly within the IEFE? No one can now get to them ! There are no outside references to them so they can never be accessed or used. What do we do now?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-uxz6DBOzRiSGHsvCi-2g.jpeg" /></figure><h4>We need to create an outside reference to those functions so that we can use those functions outside.</h4><p>How do we do that?</p><p>Yes. You are damn right. Closures to the rescue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7enf-ZCkGu6rC2_LUvHQRw.png" /></figure><p>What we have done just now is, created an inner block that wraps the forward and backward functions and return them to the calling variable; in this case, <em>mainNavigation</em>. So the variable <em>mainNavigation</em> can now be used to control the aspects of navigation. The variables <em>currentIndex</em> and <em>maxIndex </em>are now in the closure scope of these functions; and can be kept track even if the IEFE exits.</p><p>Now, look closely. What we have done here is emulating class behavior. The variables <em>currentIndex</em> and <em>maxIndex </em>are now private variables, accessible only through the member functions of the class. We have two public methods, <em>forward()</em> and <em>backward()</em> that can be used from anywhere else; and two private variables.</p><h4>This, is called the module pattern.</h4><p>Now, you have kept your code clean and maintainable. You have encapsulated different parts of your script that doesn’t have much to do with each other.</p><h4>This way, when your code base grows, you stand a fighting chance.</h4><p>Hello World. These are the writings and information I wish I had at the time I started learning JavaScript. These are inspired from various sources, accumulated over various periods of time. Follow me for more.</p><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqDjlKFwScoQYQ62DWEdig.png" /></a></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by +435,678 people.</h4><h4>Subscribe to receive <a href="https://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouK9XR4xuNWtCes-TIUNAw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf1974dbfaa9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-3-10-bf1974dbfaa9">Navigate the deepest parts of JavaScript- Closures [3/10]</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigate the deepest parts of JavaScript- Closures [2/10].]]></title>
            <link>https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-2-10-b7deac267d1?source=rss-e01fd3f8d1a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7deac267d1</guid>
            <category><![CDATA[codelikeagirl]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[aiswarya krishna]]></dc:creator>
            <pubDate>Tue, 05 Mar 2019 12:01:01 GMT</pubDate>
            <atom:updated>2020-02-28T10:40:56.512Z</atom:updated>
            <content:encoded><![CDATA[<h3>Navigate the deepest parts of JavaScript- Closures [2/10]</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMsPa7dxk67vw25KplVf9A.jpeg" /></figure><p>This is an ongoing series about intermediate JavaScript topics. If you haven’t read my first blog, please head back and take a look at the previous article (Which also happens to be the first ! )</p><p><a href="https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-1-10-a4214680b6f5">Navigate the deepest parts of JavaScript- Closures [1/10]</a></p><p>Now, you have had the much needed closure about JavaScript closures. You know how they work under the hood; and how they are used in the real world. The concept of closure is simple, but you need to understand it well. Even though syntactically simple, insufficient understanding of closures has lead to world famous memory leaks. (Will write about that in the coming weeks !) So let’s go deeper. It is time to dig much deeper and learn about some of the most common strange behaviors that has been caused by an incorrect understanding of closure. Listen closely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_dAmNs2tj6dTMEx7swDPQ.jpeg" /></figure><p>Now, let’s look at a few examples of strange behaviors from closure, and then we will get to the bottom of it <br>and then look at how closures can be used to create a design pattern in JavaScript.</p><p>See the famous interview question that follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*bIeVUtVA0hXDTdhOS7Tbmg.png" /></figure><p>If you look closely, there is an inner function and an outer function; The inner function is setTimeout, and the outer function is countTime. The variable i is in closure scope because even though the function countTime has stopped running, the setTimeout function still has access to i. So let’s ask a question; what does the above code produce?</p><p>You know that if the answer was 1,2,3, that question would look dumb. The person who wrote it obviously needed to print 1,2,3, but it won’t.</p><p>So what would be the output?</p><p>If you stare into the console, the program spits out and “4”and nothing else. What the hell?</p><p>Let’s get down to brass tacks. For that you need to have a basic understanding about how the event loop works. If you need a quick refresher, I will give you one.</p><p>JavaScript is a single threaded, event driven, non-blocking language.</p><p>Now that is something that you hear everyday.</p><h4>It is designed so, for various reasons, Avoid race conditions. Non-atomic memory access and so on. That doesn’t mean it has got only one thread.</h4><p>1. The main thread handles your code — fetch it, compile it and execute it. <br>2. There is actually a separate thread for compiling; so that our main thread can keep on executing. <br>3. There is a profiler thread for determining which methods the execution thread spends more time on, so the optimizing compiler can optimize it. <br>4. There are also a few other threads for Garbage sweeps. <br>5. If you are on node.js, then we have other threads for webAPIS, which talk to their underlying C++ counterparts.</p><p>Being single threaded means that it has only one thread handling requests. The JS engine primarily has the following components.</p><p>1. <strong>The call stack;</strong> where instruction to be executed is pushed onto the top of the stack and executed; and then popped. This is the only place from where instructions are executed.</p><p>2. <strong>The event queue:</strong> This is the limbo where the callbacks go and wait for their turn to be executed. It can be a database query or an Async API call. What the callback essentially does is, it registers a handler for the event; or the function; in the event queue and essentially tell the event loop. “Call this function when your database query has finished executing” or “Execute this function when your API call returns with data”. At first, they needs to be pushed into the stack. For this to happen; the stack should be empty. So the JS runtime, in simple terms does this in iterations. This so called “<strong><em>event loop</em></strong>” , periodically checks if the call stack is empty and if yes, it will push the first event to the callstack. This iteration is called a “tick”.</p><blockquote>Like I said, basically it’s a limbo for all the things that are waiting to be executed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5TtEIHBh-4RfhE0FpRuNg.jpeg" /></figure><p>3. <strong>Heap</strong>: This is unstructured memory the objects and other values are stores in memory. This is primarily where the garbage collector collects its garbage.</p><h4>The decoupling of the caller from the response, as happening in the event loop, allows for the JS runtime to do other better things than just waiting.</h4><p>The for loop runs three times, and it increases the value of i after each iteration. Then it sends the print command to the event queue, and on the fourth try, the value of i becomes 4, and the loop breaks execution.</p><h4>Let’s break it down:</h4><p>1. The countTime function is invoked.<br>2. The countTime function is pushed to the top of the call stack.<br>3. For loop execution begins.<br>4. For each iteration of i,<br> 1. SetTimeout method is invoked, which is pushed into the stack top.<br> 2. The console command inside the setTimeout is sent to event queue for the event loop to pick up.<br> 3. The event loop holds the console command until the call stack is clear. <br>5. The value of i becomes 4 and the for loop breaks.<br>6. for loop is popped out of the stack. <br>7. The countTime function exits; and is popped out of the stack.<br>8. Event loop checks the call stack and finds it to be empty.<br>9. Even loop pushes the first console.log(i) command into the stack frame.<br>10.The variable i is nothing but a reference to the original memory location i stored somewhere in the heap.<br>11. The current value of is is 4 (When the for loop broke)<br>12. It just print 4, and it prints it 3 times, accounting for each console.log.</p><p>So how do we fix this?</p><p>let’s see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*Jf67bBUTQgbUDkt2dWjcmQ.png" /></figure><p>Now, what we have done is, we have wrapped the inner setTimeout function inside what is known as Immediately invoked Function expression, which we shall ceremoniously call IEFE. So we now have a function inside a function.</p><p>What has changed?</p><p>When the function is invoked 3 times inside the for loop, at the beginning of each iteration; the current value of i is assigned to a local variable named currentTime. Each time the loop passes an iteration, the IEFE gets called and 3 console.log statements, with 3 currentTime (local variable) values ranging form 1 to 3 are sent to event loop. Just as the stack becomes empty, the three statements gets printed; fixing our problem.</p><h4>All we needed was a function within a function, creating a closure scope.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8CSwSg0T7A0AY0yz3fG5g.jpeg" /></figure><p>if you really look through other people’s code, you can see variations of the above code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4UQy7SdrODwn9YC0ypKkQ.png" /></figure><blockquote>In the above case, the IEFE remembers each value of i in each iteration via a variable currentTime that is passed into the function’s execution context during each loop.</blockquote><p>We don’t even have to use different variables names as i and currentTime. We can use a single variable i for that, and the code is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFOSJFk1H-J0V1MhFL8F8w.png" /></figure><p>Ta-da !! I hope you liked the article. I will write more about JS stuff like this in the coming weeks. Thanks for reading.</p><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqDjlKFwScoQYQ62DWEdig.png" /></a></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by +431,678 people.</h4><h4>Subscribe to receive <a href="https://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouK9XR4xuNWtCes-TIUNAw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7deac267d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-2-10-b7deac267d1">Navigate the deepest parts of JavaScript- Closures [2/10].</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigate the deepest parts of JavaScript- Closures [1/10]]]></title>
            <link>https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-1-10-a4214680b6f5?source=rss-e01fd3f8d1a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4214680b6f5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[aiswarya krishna]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 10:56:39 GMT</pubDate>
            <atom:updated>2020-02-28T08:56:34.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bBZnX9uHBX_YSEU2Cng_A.jpeg" /></figure><p><em>How I cracked difficult JS concepts as a beginner.</em></p><p>I often used to wonder what JavaScript was (I still do!). Years before, when I began my profession as a programmer, first as a PHP developer and then a Python programmer, I had heard about JavaScript only from the front end guys. Eventually, before my eyes, JavaScript ate its way out of all the architectural confinements and I read blogs on how it was being used for server-side coding also. Then JavaScript was suddenly everywhere-omni-present, from Websites to light bulbs - just like Java was once, before the big ugly Oracle came up and swallowed it. I often wondered why it was a paradox — the most loved as well as the most hated language in the world at the same time; existing inside the grey area where the black and the white intersected.</p><p>Years later, here I am now, venturing into JavaScript, writing down some topics about which I wish I had got advice and classes about at the time I began. I had to refer a lot of materials to understand a few concepts. Being from an OOPS background; but with no real Java experience other than some projects at college, I struggled to find peace to understand the prototype based structuring of JavaScript apps. I am writing these down to help anyone who is undergoing the same journey. This is not rocket science, but I do hope that it helps you.</p><p>I assume that those who read it have basic understanding about JavaScript.</p><p>Now let’s venture into closures.</p><p>Before starting officially with closures, I want you to understand what <em>Scop</em>e is, and what <em>Garbage Collection</em> in JavaScript is.</p><h3>Scope.</h3><p>Scope means a region of the program which can see or use a variable. In other words, the visibility of variables. The importance of scope arises because the JavaScript engine has to have a way to efficiently manage memory. Obviously it can task the users with destroying the objects which are no longer in use. But how can it trust humans? We forget, and ignorance is bliss for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqtmqdxK4CZXscZq4eOsqA.jpeg" /></figure><p>To add insult to injury, unlike languages such as C, ECMAScript, lacks that particular interface to access memory management. That means no API. It means memory management rights in a program get passed over to the engine itself. That means, if we screw up, no amount of programmer dark magic can save us.</p><p>The result of us screwing up? The allocated objects blog down the memory like a New York City lane caught in a traffic jam. No matter how many cars you try to squeeze, the lane comes to a standstill and then you are going to have a console as red as a game of thrones wedding.</p><p><em>You have a heap out of memory scenario.</em></p><h4><strong>What is garbage collection?</strong></h4><p>The program can’t blog down the entire memory heap because it keeps unused variables or objects in memory. That means, it needs to have a smart way to remove variables that are out of scope. It is where garbage collector comes in, whose job is to track down memory allocation in order to find when a piece of allocated memory is not needed anymore. But this is the hardest part. In all high level and low level languages, this process is nothing but an approximation; since the general problem is undecidable by an algorithm. This problem is either achieved by collecting all objects to which no references exist, or a mark and sweep algorithm, which would sweep all allocations that are not reachable. Under the hood, every engine has its own garbage collection heuristics, but all of them are basically doing either of these, or both of them. The components of V8 JavaScript optimization engine —<em> the full-Codegen and Crankshaft</em>, which powers the v8 has gotten much smarter since then, employing other smarter means to collect garbage. (Full codeGen and Crankshaft has been replaced by <em>Ignition and Turbofan</em> previous year, V8’s new interpreter and optimizing compiler. They shipped out previous year in V8 5.9)</p><p>But what happens when we can have significant efficiency gains by not letting the garbage collector collect certain out-of-scope objects?</p><p>That’s where closure comes in.</p><p>Let’s imagine the following scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C42rQELqVwDx06WgPk6dsQ.png" /></figure><p>Here, after the function call has ended, the call stack pops out the function statement. The garbage trucks all come in, ready to haul away your orphan objects, and whatever objects that were declared or used inside the function is to be killed and collected and then released to the heap pool for other variables to live and thrive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQ7LJcfjF1uSOTB_UwVKbg.jpeg" /></figure><p>But hey, stop and think about the state of <em>outer_var1</em> after the function has ended? Why do you care, you may ask. It was just a variable that was trapped in the function scope and after<em> outerFunction</em> has run, where is it? It doesn’t matter. You can’t use it anyway. No use for us anyway. But let’s modify the code a little bit and see where this leads us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-QAt4lVu9h8dG3vSsS8pg.png" /></figure><p>If you print out the type of object stored in sampler, you get that the type is “function”. So what? You may ask. Functions are first class citizens in JavaScript and can be passed around or returned from functions. But the caveat here is that, when the internal function returned, it created a new scope — a <strong><em>closure scope</em></strong>, which allows us to access a function scoped variable after the function has exited. You can invoke the sampler function, and it has access to the variable <em>outer_var1</em>, <strong>even after <em>outerFunction</em> has existed.</strong></p><p>So what happens to the Garbage trucks? Let’s see what happens below.</p><ol><li>The <em>outerFunction()</em> is invoked.</li></ol><p>2. It creates a new execution context and binds it to “this”.</p><p>3. It declares the function scoped variable <em>outer_var1</em> as 10.</p><p>4. It returns the<em> innerFunction()</em>, which is stored in the sampler variable.</p><p>5. The <em>outerFunction</em> is popped out of the call stack.</p><p>6. Garbage trucks arrive to haul away what was left of the <em>outerFunction</em>, and it makes sense that the variable <em>outer_val1</em> will also be collected.</p><p>But alas, sitting comfy inside the inner function is a reference to the outer variable, preventing it from being collected.</p><p><em>var sum = outer_var1 + inner_var1;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7G-Khsz-MWDLWD-17yQHvw.jpeg" /></figure><p><strong>Where do we possibly need to use closures in real life?</strong></p><p>We all known JavaScript is a dynamically typed, functional programming language. When run upon powerful engines like Google’s V8, like in the case of node.js and React, JavaScript becomes so powerful. It is a mistake to say that it is purely functional. The language has grown past numerous specifications, with the help of closures; we can emulate Object oriented behavior in JavaScript. Closures are mainly used to,</p><ol><li>Emulate class behavior in JavaScript by encapsulating functions and variables — The Module pattern.</li></ol><p>2. Function factories.</p><p>3. Memoization.</p><h3>#1: Memoization: Case study.</h3><p>Let’s consider the following example. The objective is to write a function that takes in a number n, and print the nth prime number. Now, this is not an ideal example as this scenario doesn’t arise in day to day life. But this example serves as a perfect example But when it does, you don’t need to be on the dark side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0Kc7XjG_z_20agWXfNgJw.png" /></figure><p>The variable current holds the number we are currently checking for being a prime. The variable counter holds the total number of primes we have found thus far. The array primes is the actual list of the prime numbers found.</p><p>In this case, if you notice, the variables current, counter and prime are inside the lexical scope of the <strong><em>searchNthPrime</em></strong> function. They are the control variables that governs the state of the prime loop. When the function exists, these control variables are collected away by the garbage collector.</p><p><em>“Good Riddance” You say.</em></p><p>Now, as we increase the value of n, it progressively becomes computationally expensive.</p><p>Try calling searchNthPrime(10000), it gives 104,729, which is the 10000th prime number.</p><p>Now again call the function, but this time pass over 10001, as searchNthPrime(10001)</p><p>It still takes a few seconds to output the number 104,743.</p><h4>Something is wrong.</h4><p>Even if we calculate 10000th prime number, like <em>searchNthPrime(10000)</em>, the next time we pass over <em>searchNthPrime(10001)</em>, the function will iterate from the beginning all over. So you ask, yourselves. <em>No ! The JavaScript engine has to be smart enough to understand that we might not need to start from the start. Somehow, it has to be smart enough to memorize the control variables for the next time.</em></p><p>Yeah. They know. That’s why they have created the closure scope.</p><p>Now let’s rewrite the code as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-VoZODtpLOK437mMG_qWQ.png" /></figure><p>Now, try running<em> findPrime(10000)</em>. It will print out 104,729.<br>try calling <em>findPrime(10001)</em>. It prints 104,743 within nanoseconds.</p><h4>Voila !!</h4><p>We have successfully used closures to create a memoization of the control variables. What happens here is, the outer function encloses the inner function and the control variables into a <em>closure scope</em> and then returns the function along with this scope. This inner function, <em>searchNthPrime(10000) </em>has access to the control variables, outside the scope of the <em>setNthPrime </em>function. aka the outer function. So when you first run the function, to calculate 10000th prime, these variables acquire a value. This value is not garbage collected because the returned function still reference to it from the outside; from inside the <em>findPrime </em>variable, which now holds a function. When we run the second function call, the control variables resume from their current value...meaning, they will start from values that correspond to 10000th prime number. Not 1.</p><p>Closures are used in two more scenarios:</p><ol><li>Create a function factory.</li><li>Create module design pattern.</li></ol><p>These will be explored from the scratch in my next blog. Closures also have caused world famous memory leaks, about which I will write in the coming days. Stay tuned. Thank you for reading. !!</p><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqDjlKFwScoQYQ62DWEdig.png" /></a></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by +426,678 people.</h4><h4>Subscribe to receive <a href="https://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><a href="https://medium.com/swlh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouK9XR4xuNWtCes-TIUNAw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4214680b6f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/navigate-the-deepest-parts-of-javascript-closures-1-10-a4214680b6f5">Navigate the deepest parts of JavaScript- Closures [1/10]</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>