<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ closure - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ closure - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:30:24 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/closure/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Closures Work in JavaScript: A Handbook for Developers ]]>
                </title>
                <description>
                    <![CDATA[ If you're learning JavaScript, you've probably heard the term "closure" at some point. In many developers' experience, just hearing this word can trigger anxiety. In nearly 17 years of programming experience, I've noticed that closures are one of the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-closures-work-in-javascript-a-handbook-for-developers/</link>
                <guid isPermaLink="false">6925c63dff3af82fd3477d27</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ closures in javascript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sumit Saha ]]>
                </dc:creator>
                <pubDate>Fri, 16 Jan 2026 08:00:00 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1764083198713/3afde98a-fecd-4669-a2ad-3d78c28d3d5a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're learning JavaScript, you've probably heard the term "closure" at some point. In many developers' experience, just hearing this word can trigger anxiety. In nearly 17 years of programming experience, I've noticed that closures are one of the most intimidating topics for JavaScript developers, even though they shouldn't be.</p>
<p>The main goal of this handbook is to remove that fear. By the end of this guide, you should be able to confidently say, "I’m not afraid of closures anymore!"</p>
<p>Closures aren't actually that complicated at all when you break them down. They just might seem harder to grasp while you don't understand them clearly. Many articles or tutorials don't explain the topic deeply, which leaves you confused, asking questions like, "What exactly is a closure?" or "What does it really mean?"</p>
<p>Throughout this handbook, I'll walk you through several examples step by step. If you stick with this guide until the end, I promise – all your confusion about closures should disappear.</p>
<h2 id="heading-heres-what-well-cover">Here’s What We’ll Cover</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-project-setup-before-learning-closures">Project Setup Before Learning Closures</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-create-a-new-project-folder">Create a New Project Folder</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-create-the-indexhtml-file">Create the index.html File</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-create-the-script-folder-seven-example-files">Create the script Folder + Seven Example Files</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-very-important-note">Very Important Note</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-run-the-project">Run the Project</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-functions-and-parameters-the-basics">Functions and Parameters - The Basics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-accessing-variables-without-parameters">Accessing Variables Without Parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-scope-and-lexical-scoping">Understanding Scope and Lexical Scoping</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-closure">What is a Closure?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-functions-as-objects">Functions as Objects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-function-parent-relationship">The Function-Parent Relationship</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-nested-functions-and-closures">Nested Functions and Closures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-refining-the-example">Refining the Example</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-creating-private-properties-with-closures">Creating Private Properties with Closures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-role-of-closures-in-privacy">The Role of Closures in Privacy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-closure-mechanics">Understanding Closure Mechanics</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-how-closures-make-decisions">How Closures Make Decisions</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-closures-and-enclosing-scopes">Closures and Enclosing Scopes</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-documentation-definition">The Documentation Definition</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-enclosing-scope-concept">The Enclosing Scope Concept</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-interpreting-the-closure-definition">Interpreting the Closure Definition</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-example-self-contained-closures">Practical Example - Self-Contained Closures</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-understanding-references">Understanding References</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-the-difference-between-var-and-let">The Difference Between var and let</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-understanding-var-and-let-scoping">Understanding var and let Scoping</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-observing-the-difference">Observing the Difference</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-iife-with-let">Using IIFE with let</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-closures-through-a-practical-stopwatch-example">Understanding Closures Through a Practical Stopwatch Example</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-defining-the-stopwatch-function">Defining the Stopwatch Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-the-stopwatch">Using the Stopwatch</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-calling-the-timer-function">Calling the Timer Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-inspecting-the-timer-function">Inspecting the Timer Function</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-closures-and-garbage-collection">Closures and Garbage Collection</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-closures-in-asynchronous-code">Closures in Asynchronous Code</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-basic-asynchronous-example-with-settimeout">Basic Asynchronous Example with setTimeout</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-external-function-reference-example">External Function Reference Example</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-example-api-requests-with-closures">Practical Example: API Requests with Closures</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-refactoring-with-external-function">Refactoring with External Function</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-advanced-example-closures-in-loops">Advanced Example - Closures in Loops</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-synchronous-loop-example">Synchronous Loop Example</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-asynchronous-loop-example">Asynchronous Loop Example</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-var-vs-let-problem">The var vs let Problem</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-consoledir-with-loop-closures">Using console.dir with Loop Closures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-var-loop-problem">The var Loop Problem</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-fixing-the-var-loop-problem-with-iife">Fixing the var Loop Problem with IIFE</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-and-key-takeaways">Summary and Key Takeaways</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-closure-1">What is a Closure?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-main-ideas-in-this-guide">The Main Ideas in This Guide</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-importance-of-closures">The Importance of Closures</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-final-words">Final Words</a></p>
</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along and get the most out of this guide, you should have:</p>
<ol>
<li><p>Basic JavaScript (ES6-style) knowledge</p>
</li>
<li><p>Familiarity with browser developer tools</p>
</li>
<li><p>Comfort with asynchronous code (promises)</p>
</li>
<li><p>Basic ability to use the terminal/command line</p>
</li>
<li><p>Familiarity with a code editor like VS Code – Live Server extension (for running HTML files locally)</p>
</li>
</ol>
<p>I’ve also created a video to go along with this article. If you’re the type who likes to learn from video as well as text, you can check it out below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/JVT_d9Qx_ro" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-project-setup-before-learning-closures">Project Setup Before Learning Closures</h2>
<p>Closures are an amazing concept in JavaScript. But if you jump into the code without preparation, they can feel a bit intimidating.</p>
<p>So before we start exploring closures, let's set up a simple, clean project where you can test each example comfortably. Once this setup is done, you won't need to repeat it again and again throughout the article. So follow along carefully and you'll prepare everything at once.</p>
<h3 id="heading-create-a-new-project-folder">Create a New Project Folder</h3>
<p>Open your terminal and run:</p>
<pre><code class="lang-bash">mkdir closure
<span class="hljs-built_in">cd</span> closure
</code></pre>
<p>This folder will contain your main HTML file and all the JavaScript examples.</p>
<h3 id="heading-create-the-indexhtml-file">Create the index.html File</h3>
<p>Now create the HTML file:</p>
<pre><code class="lang-bash">touch index.html
</code></pre>
<p>Open <code>index.html</code> and add the following code:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Closure Tutorial | LogicBase Labs<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script/example-1.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script/example-2.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script/example-3.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script/example-4.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script/example-5.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script/example-6.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script/example-7.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h4 id="heading-why-so-many">Why so many <code>&lt;script&gt;</code> tags?</h4>
<p>Good question! In this tutorial, you'll explore closures in <strong>7 different ways</strong>. Each example will live in its own JavaScript file, so things stay clean and beginner-friendly. If you tried to put everything inside one file, the outputs would get mixed up and confusing. That's why you're loading each example separately.</p>
<h3 id="heading-create-the-script-folder-seven-example-files">Create the <code>script</code> Folder + Seven Example Files</h3>
<p>Let's create a folder named <strong>script</strong>:</p>
<pre><code class="lang-bash">mkdir script
<span class="hljs-built_in">cd</span> script
</code></pre>
<p>Now create the seven example files:</p>
<pre><code class="lang-bash">touch example-1.js
touch example-2.js
touch example-3.js
touch example-4.js
touch example-5.js
touch example-6.js
touch example-7.js
</code></pre>
<p>You'll write and test each closure example inside these files.</p>
<h3 id="heading-very-important-note">Very Important Note:</h3>
<p>If all 7 files run at the same time, your console output will get mixed up. You won't understand which message came from which example.</p>
<p>So here's the rule:</p>
<ul>
<li><p>When working on <code>example-1.js</code>, comment out the rest.</p>
</li>
<li><p>When working on <code>example-3.js</code>, uncomment that one only, and comment out the others.</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- &lt;script src="./script/example-1.js"&gt;&lt;/script&gt; --&gt;</span>
<span class="hljs-comment">&lt;!-- &lt;script src="./script/example-2.js"&gt;&lt;/script&gt; --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script/example-3.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-comment">&lt;!-- &lt;script src="./script/example-4.js"&gt;&lt;/script&gt; --&gt;</span>
<span class="hljs-comment">&lt;!-- &lt;script src="./script/example-5.js"&gt;&lt;/script&gt; --&gt;</span>
<span class="hljs-comment">&lt;!-- &lt;script src="./script/example-6.js"&gt;&lt;/script&gt; --&gt;</span>
<span class="hljs-comment">&lt;!-- &lt;script src="./script/example-7.js"&gt;&lt;/script&gt; --&gt;</span>
</code></pre>
<p>This keeps your output clean, clear, and conflict-free.</p>
<h3 id="heading-run-the-project">Run the Project</h3>
<p>Open <strong>Live Server</strong> from VS Code and you'll see: <a target="_blank" href="http://127.0.0.1:5500/closure/index.html">http://127.0.0.1:5500/closure/index.html</a></p>
<p>This is your working route. Inside this project, you'll explore the full world of closures step by step. Now you're ready to dive into closures and learn what they are, how they work, and why closures are one of the most powerful concepts in JavaScript.</p>
<h2 id="heading-functions-and-parameters-the-basics">Functions and Parameters – The Basics</h2>
<p>So now you will mainly work on the <code>example-1.js</code> file. Listen, throughout this entire handbook, you will first write the full code, and then we’ll go line by line to understand the breakdown in detail. There's nothing to worry about: we will uncover every single thing in its full depth.</p>
<p><strong>Full code:</strong> <code>example-1.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-1.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));
</code></pre>
<p>Usually, when you want to use an outside variable inside a function, you pass it as a parameter. For example, consider a function called <code>sum</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">num1, num2</span>)</span>
</code></pre>
<p>Here, two numbers are taken as parameters. To add these numbers and return the result:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> num1 + num2;
</code></pre>
<p>To see the output:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));
</code></pre>
<p>The output will be <code>5</code>. Simple, right?</p>
<h2 id="heading-accessing-variables-without-parameters">Accessing Variables Without Parameters</h2>
<p><strong>Full code:</strong> <code>example-1.js</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-built_in">console</span>.log(sum());
</code></pre>
<p>But in JavaScript, there's a way to do the same thing without passing parameters. Let's remove the parameters from the <code>sum</code> function. Instead, you'll define two variables in the global scope:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
</code></pre>
<p>Now, when you call <code>sum()</code>, the output will still be <code>5</code>.</p>
<p>The question is: <em>“how does JavaScript do this?”</em> It seems strange, right? Inside a function, you're using variables that don't actually belong to that function – they exist outside in the wider environment where the function was created. In simple terms, the function is using variables from its parent scope.</p>
<h2 id="heading-understanding-scope-and-lexical-scoping">Understanding Scope and Lexical Scoping</h2>
<p>This concept relates to one of the most fundamental principles in JavaScript: everything from a parent is accessible to the child. If there were nested functions inside this function, even the deepest child function could access variables like <code>num1</code> and <code>num2</code> from the parent. The parent's variables are fully accessible to the child, but nothing from the child can be accessed by the parent.</p>
<p>I’ve already covered this topic in a detailed video on <strong>JavaScript Scope</strong> on the LogicBase Labs YouTube channel. If you'd like to revisit the concept or get a quick refresher, you can watch the video below.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/NtHgwL3uubk" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>For example, if you define a new variable inside the <code>sum</code> function, it cannot be accessed from outside the function. This is the core idea of scope. This system of scope is theoretically called <strong>Lexical Scoping</strong>. Since today's topic is Closures, understanding scope is essential, as closures and scope are deeply connected.</p>
<p>According to lexical scoping, a child function can access its parent's variables, but a parent cannot access the child's. This isn't random – it's a specific convention or guideline in JavaScript.</p>
<h2 id="heading-what-is-a-closure">What is a Closure?</h2>
<p>The word "closure" literally means a "bond" or "enclosure." Think of it like keeping a variable safely locked away, just like storing something inside a box.</p>
<p>Even though the box is closed, you can still use its contents when needed. This is why it's called a closure: because you keep a function's variables enclosed in such a way that, even if the outside world cannot access them directly, the function itself can still use them whenever required.</p>
<h2 id="heading-functions-as-objects">Functions as Objects</h2>
<p>In JavaScript, whenever you write a function, the function is actually treated as an object. Every function in JavaScript works as an object. Just as you can <code>console.log</code> an object to see it, you can also inspect a function.</p>
<p>Let's print our <code>sum</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(sum);
</code></pre>
<p>Notice that you're not calling the function. Rather, you're just printing its body. You use <code>dir</code> instead of <code>log</code> because <code>console.log</code> only shows the function body, while <code>console.dir</code> displays the function as an object, letting you see each of its properties one by one. You can think of it as an upgraded version of <code>console.log</code>.</p>
<p>Looking at the output, you'll see an object. Expanding it reveals many properties, like <code>name</code>, <code>length</code>, <code>prototype</code>, and more. At the very bottom, there's a property called <code>Scopes</code>. Inside <code>Scopes</code>, there's a section named <code>Global</code> containing further details. The <code>Scopes</code> property is what we’ll mainly focus on here.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763460615059/210b2880-7cb7-4161-ac75-c67d196341ed.png" alt="Nested Function and Closure" width="1920" height="1080" loading="lazy"></p>
<h2 id="heading-the-function-parent-relationship">The Function-Parent Relationship</h2>
<p>Notice something here: the <code>sum</code> function has its own world, right? So why is it still referencing the global scope?</p>
<p>Every function actually maintains a connection with its parent environment. It doesn't just live in its own world – it keeps a link to the environment where it was created. Simply put, it always holds a reference to its parent.</p>
<p>Why does it do this? Because if anything changes in the parent environment (like a variable's value or the need to use it inside the function), the function can still access it.</p>
<p>This whole process is the core concept of a closure. A function keeps track of the variables it uses from outside its own scope by closing over its parent, and its parent's parent – essentially the entire scope chain above it – holds them as references.</p>
<p>That's why this example is actually the simplest form of a closure. The <code>sum</code> function itself is a closure because it has captured some variables from its outer environment and can use them whenever needed.</p>
<p>Even though you often see closures explained with examples where "a function is inside another function," the fundamental idea starts here: <em>“any function that retains access to variables from its outer scope is, in essence, a closure.”</em></p>
<h2 id="heading-nested-functions-and-closures">Nested Functions and Closures</h2>
<p><strong>Full code:</strong> <code>example-1.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-1.js</span>
<span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> num1 + num2;
    };
}

<span class="hljs-keyword">var</span> myFunc = sum();

<span class="hljs-built_in">console</span>.dir(myFunc);
</code></pre>
<p>You can understand this even more clearly by tweaking the previous <code>sum</code> function. Instead of directly returning a value, you'll have the <code>sum</code> function return another function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{};
</code></pre>
<p>And inside this inner function, you write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> num1 + num2;
</code></pre>
<p>So what does this mean? The <code>sum</code> function is no longer returning a value directly. Instead, it's returning a function.</p>
<p>Now, create another variable called <code>myFunc</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> myFunc = sum();
</code></pre>
<p>You called the <code>sum</code> function, and whatever it returned (the inner function) is now stored in <code>myFunc</code>. In other words, <code>myFunc</code> is essentially the inner function returned by <code>sum</code>.</p>
<p>If you print <code>myFunc</code> to the console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(myFunc);
</code></pre>
<p>You'll see <code>num1</code> and <code>num2</code> listed as variables in the output. This function is still holding onto its global environment. Even though it's an inner function, it's still connected to the global scope and maintains the same global references as before.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763460615059/210b2880-7cb7-4161-ac75-c67d196341ed.png" alt="Nested Function and Closure" width="1920" height="1080" loading="lazy"></p>
<h2 id="heading-refining-the-example">Refining the Example</h2>
<p><strong>Full code:</strong> <code>example-1.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-1.js</span>
<span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> num1 + num2;
    };
}

<span class="hljs-keyword">var</span> myFunc = sum();

<span class="hljs-built_in">console</span>.dir(myFunc);
</code></pre>
<p>Now, remove the <code>num2</code> variable from the global scope and define it inside the <code>sum</code> function instead.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763463873933/84153aca-ee54-476d-99be-4b638926c0f4.gif" alt="Refine the closure" width="1138" height="640" loading="lazy"></p>
<p>This time, in the browser, you can clearly see something labeled "Closure." In other words, the browser is directly showing that a closure has been created inside this function.</p>
<p>In older versions of Chrome, you would have seen "Closure" in the previous example too. But in the newer versions, it shows as "Global" until a function actually closes over another function. When a function is returned from within another function, that's when the browser displays "Closure." But keep in mind that theoretically, the previous example was also a kind of closure. The difference is just in how the browser presents it.</p>
<p>When you did <code>console.dir(myFunc)</code>, you saw that this inner function is using both <code>num1</code> and <code>num2</code>:</p>
<ul>
<li><p><code>num1</code> is in the global scope</p>
</li>
<li><p><code>num2</code> is inside the <code>sum</code> function's scope</p>
</li>
</ul>
<p>So what is this inner function doing? It's taking a reference to <code>num1</code> from the global scope and at the same time taking a reference to <code>num2</code> from its parent function, <code>sum</code>. In other words, this inner function now carries two worlds within it: one is the global scope, and the other is its parent scope. This is exactly what a closure does: it keeps all the outer scopes it needs "enclosed" so it can use their variables whenever necessary.</p>
<p>In the browser, you can see that inside this closure, <code>num2</code> exists, while <code>num1</code> remains in the global scope. So <code>num1</code> is no longer part of the closure. What does this mean? The function only carries the parts of the environment it actually needs for its execution. Simply put, it takes all the variables it needs, along with their references, as a compact package.</p>
<p>Think of it like the function holding onto references: whenever any of these variables are updated, the function can see those changes because it's still connected to the same references.</p>
<p>If you called <code>myFunc = sum()</code> once and keep calling <code>sum()</code> repeatedly, there's no problem. Each time, a new function will create its own separate scope and keep a reference to that scope. You defined a function and then called it elsewhere. Every time you call that function, it can still access the data from its previous scope. That's because every function preserves all the information from its parent scope as references. This is exactly how a function remembers its outer variables – and this is what a closure is.</p>
<h2 id="heading-creating-private-properties-with-closures">Creating Private Properties with Closures</h2>
<p>So far, all the examples you've seen were very simple. Now, let's look at a practical example that will help you understand closures better and clear up any confusion.</p>
<p>Think about other programming languages for a minute: when you want to create a private property, what do you usually do? You define a property inside a class and mark it as "private" so that no one can access it directly from outside the class. Then, inside the class, you create one or more public functions (like getters or setters) which allow controlled access to or modification of that property. In other words, you can't touch the property directly from outside – you can only interact with it through specific functions defined inside the class.</p>
<p>In JavaScript, you can achieve the same idea much more simply using closures, entirely in a functional style.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763463928785/5e2d10bf-0e21-420d-8c27-576ab7172896.gif" alt="Creating private property" width="1138" height="640" loading="lazy"></p>
<p>How? Let's see an example. Suppose you have a simple function:</p>
<p><strong>Full code:</strong> <code>example-2.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-2.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bankAccount</span>(<span class="hljs-params">initialBalance</span>) </span>{
    <span class="hljs-keyword">var</span> balance = initialBalance;

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> balance;
    };
}
<span class="hljs-keyword">var</span> account = bankAccount(<span class="hljs-number">100000</span>);

<span class="hljs-built_in">console</span>.log(account());
<span class="hljs-built_in">console</span>.dir(account);
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bankAccount</span>(<span class="hljs-params">initialBalance</span>) </span>{}
</code></pre>
<p>You've named it <code>bankAccount</code>, and it takes the user's initial balance as a parameter.</p>
<p>Inside it, define a variable:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> balance = initialBalance;
</code></pre>
<p>So, the user's initial balance is stored internally in a variable called <code>balance</code>. Next, return a function that returns this <code>balance</code> variable. In other words, the balance can only be accessed through this returned function.</p>
<p>Outside, in the global scope, create a variable:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> account = bankAccount(<span class="hljs-number">100000</span>);
</code></pre>
<p>Here, you called the <code>bankAccount</code> function and passed 100000 as the initial balance. What is this function actually doing? It's returning another function. So now, the <code>account</code> variable holds that returned function.</p>
<p>If you write in the console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(account());
</code></pre>
<p>The output will be 100000.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763463963441/8104145d-b908-4131-8a6b-3c4c3ad88434.png" alt="Private Property Output" width="1920" height="1080" loading="lazy"></p>
<p>But if you try this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(balance);
</code></pre>
<p>it won't work, because the <code>balance</code> variable cannot be accessed from outside.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763463984564/6c70013b-6566-4bf2-a517-bea3672022e1.png" alt="Error Output" width="2880" height="1800" loading="lazy"></p>
<p>What does this mean? The <code>balance</code> property is protected or private. No one from the outside can directly touch it. To see the balance, you can only call the returned function inside the original function. This is how you keep <code>balance</code> as a private variable and control access to it.</p>
<h2 id="heading-the-role-of-closures-in-privacy">The Role of Closures in Privacy</h2>
<p>So, what's the role of the closure here? It's exactly what makes this possible. The inner function is the closure. If you write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(account);
</code></pre>
<p>You'll see that inside the <code>account</code> function is the returned function.</p>
<p>By taking the output and expanding it, you'll see that the <code>balance</code> variable exists inside the closure. Exactly, right? This means that <code>balance</code> wasn't created inside the <code>account</code> function itself – it was created one scope level up. Yet, you can still access <code>balance</code> from the returned function.</p>
<p>It's similar to the previous example, but this use case is slightly different. Here, you're showing how a private property can be kept secure. Even though you called the inner function from the outside, it still had access to <code>balance</code> within its scope. So, the outer scope cannot directly access <code>balance</code>, but thanks to the closure, you can maintain a reference to it. Even though the function is called from outside, the closure allows you to access the private property in a protected way.</p>
<p>Why protected? Because you're not accessing it directly – you can only see <code>balance</code> through the function call.</p>
<p>💡This is another powerful use case of closures: securing private properties so that they can't be directly accessed from outside, but only through specific functions.</p>
<h2 id="heading-understanding-closure-mechanics">Understanding Closure Mechanics</h2>
<h3 id="heading-how-closures-make-decisions">How Closures Make Decisions</h3>
<p>Now, let’s look at another aspect of closures. We’ll revisit our first example.</p>
<p><strong>Previous code:</strong> <code>example-1.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-1.js</span>
<span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> num1 + num2;
    };
}

<span class="hljs-keyword">var</span> myFunc = sum();

<span class="hljs-built_in">console</span>.dir(myFunc);
</code></pre>
<p>In that example, you used a variable called <code>num2</code> inside the inner function. That's why the function acted as a closure, right?</p>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
<span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> num1;
    };
}
<span class="hljs-keyword">var</span> myFunc = sum();
<span class="hljs-built_in">console</span>.dir(myFunc);
</code></pre>
<p>Now, keep the variable but stop using <code>num2</code> inside the inner function. If you check the output, you'll see that the closure is gone. Why?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464099671/a34e465a-ed85-4631-8a0d-07e681cecc52.png" alt="Closure Gone Output" width="1920" height="1080" loading="lazy"></p>
<p>It's because <code>num2</code> isn't used inside the inner function. JavaScript smartly recognizes that this variable isn't needed, so it's not included in the closure. In other words, JavaScript decides on its own: variables that won't be used inside the function, even if they exist in the outer scope, are not included in the closure. Only the variables that the function actually needs become part of the closure.</p>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
<span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
    <span class="hljs-keyword">var</span> num = <span class="hljs-number">6</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> num;
    };
}
<span class="hljs-keyword">var</span> myFunc = sum();
<span class="hljs-built_in">console</span>.dir(myFunc);
</code></pre>
<p>For example, if you define another variable inside the <code>sum</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> num = <span class="hljs-number">6</span>;
</code></pre>
<p>and do nothing else, there's still no need for a closure. But if you modify the inner function to return <code>num</code> instead of <code>num1</code>, the closure appears again. This time, the closure contains only <code>num</code>. <code>num2</code> won't be there, but <code>num1</code> remains because it exists in the global scope. JavaScript preserves this scope to maintain lexical scoping.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464124937/3a155661-838d-4070-a8ab-e6c283a0838f.png" alt="Closure with num Output" width="2560" height="1440" loading="lazy"></p>
<p>If you look at the global scope, you can still see <code>num1</code>. That's because you used the <code>var</code> keyword. If you had used <code>let</code>, it wouldn't be visible. The key difference you're noticing is: <code>num1</code> exists in the global scope, so it remains in the closure's "environment," but if a variable inside the inner function isn't used, it's not included in the closure.</p>
<p>For example, if you use <code>num1</code>, you're accessing the global variable. So what happens now? Will there be a closure? Look, there isn't one. Since <code>num1</code> exists in the global scope, there's no extra need. The global scope is sufficient, and no separate closure is required. This shows how closures actually work.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464145498/68d704f4-f614-49e9-929f-735880ef374a.png" alt="No Closure with Global Output" width="2560" height="1440" loading="lazy"></p>
<p>A closure decides which variables need to be kept inside the function and which don't. JavaScript makes this decision automatically. You just need to remember lexical scoping so that outer scope variables can be accessed.</p>
<p>In simple terms, closures make intelligent decisions. Variables used inside the function are kept "inside," variables in outer scopes that aren't used aren't included, and global variables are accessible directly, so there's no need to include them in the closure.</p>
<p>So here, you kept <code>num1</code>, and it exists in the global scope. The function can access it directly from there. But if the inner function used only <code>num</code> – which doesn't exist in its own scope or globally – then a closure would have to be created to carry that variable along.</p>
<p>In short, a closure doesn't wrap everything. It doesn't include variables that are already outside. This is an important point. Another important point is that global scope variables are never included in closures.</p>
<h2 id="heading-closures-and-enclosing-scopes">Closures and Enclosing Scopes</h2>
<h3 id="heading-the-documentation-definition">The Documentation Definition</h3>
<p>Often, there's some confusion about when a closure appears and when it just shows global. Even senior interviewers sometimes hesitate to call the global scope a closure at first glance.</p>
<p>If you look at the JavaScript documentation maintained by Mozilla, the 2016 docs highlighted something important.</p>
<p>In the definition, it stated:</p>
<blockquote>
<p>"variables that are used locally, but defined in an enclosing scope" (<a target="_blank" href="https://web.archive.org/web/20160722004334/https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">Reference</a>)</p>
</blockquote>
<p>This refers to variables that are used locally inside a function but are actually defined in an outer scope. This is key. Only variables that are actually used inside a function are included in the closure. Variables that exist in an outer scope but aren't used inside the function aren't part of the closure.</p>
<p>In simple terms, a closure is a function that remembers its local scope along with the necessary variables from an outer scope, so even if the function is called from outside, it can still access those variables.</p>
<h3 id="heading-the-enclosing-scope-concept">The Enclosing Scope Concept</h3>
<p>Suppose you have a variable <code>num</code> defined outside, but you use it locally inside the function. That's why the browser shows it as a closure, just like the documentation says.</p>
<p><strong>Full Code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
<span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
    <span class="hljs-keyword">return</span> num1 + num2;
}
<span class="hljs-built_in">console</span>.dir(sum);
</code></pre>
<p>But if you don't use the outer variable inside the returned function, what happens? If you removed everything else and just returned <code>num1 + num2</code>, the <code>sum</code> function would work fine. But if you do <code>console.dir(sum)</code>, the word "closure" doesn't appear.</p>
<p>Why? Because <code>num2</code> is local inside the function, and there's no need to include it in a closure. A closure is only needed to use variables from an outer scope. Since this is the very first-level outer scope (meaning the global scope) and it's not inside any function, the <code>sum</code> function is already capturing it in its own scope. So no additional closure is created.</p>
<p>The critical question is: <em>“when does the browser show a closure, and when doesn't it?”</em> The explanation comes from the documentation: "variables that are used locally, but defined in an enclosing scope." Your <code>num1</code> variable is defined outside but used locally inside. But <code>num1</code> doesn't have any enclosing scope. Here, an enclosing scope means a scope that wraps around another scope – inside a set of brackets. But <code>num1</code> is directly in the global scope, not inside any enclosing scope.</p>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
        <span class="hljs-keyword">return</span> num1 + num2;
    }

    <span class="hljs-built_in">console</span>.dir(sum);
})();
</code></pre>
<p>If you want to bring this into an enclosing scope, you need to wrap the whole thing inside a function. You can write an anonymous function like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{}
</code></pre>
<p>Then you put everything inside that function and immediately call it. This is known as an <strong>Immediately Invoked Function Expression</strong> (IIFE for short). It’s basically a function that gets defined and executed at the same time.</p>
<p>When you use an IIFE, everything gets moved into an enclosing scope. The <code>num1</code> that was previously open in the global scope is now inside this function. So it's now part of an enclosing scope. If you check in the browser and expand it, you see the word "closure."</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464214402/43092c54-012f-42be-a7ea-d25c4d15eb90.png" alt="Closure with Enclosing Scope Output" width="2560" height="1440" loading="lazy"></p>
<p>That's because you've brought the variables into an enclosing scope. The browser now shows it as a closure.</p>
<h3 id="heading-interpreting-the-closure-definition">Interpreting the Closure Definition</h3>
<p>If someone ever gets confused or disagrees, they might say, "The outer one isn't a closure, it's just the global scope." But theoretically, you can still consider it a closure. Some might insist, "That's a closure," while others may not agree.</p>
<p>The thing is, JavaScript always keeps the global scope intact to maintain lexical scoping. People who disagree might say, "The global scope is just preserved, that's not a closure." And that's fair. But the concept is really the same. If a variable from an outer scope is used or referenced inside a function, it behaves just like a closure. The idea is consistent.</p>
<p>There's a small difference though: the global scope keeps all variables that exist outside any function. That's why some might argue it's not technically a closure. But from a theoretical perspective, it behaves like one, with only minor differences for global variables.</p>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
<span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-built_in">console</span>.dir(sum);
</code></pre>
<p>If you didn't use an IIFE and went back to the previous setup, the browser would no longer show it as a closure. And the <code>var num1</code> is in the global scope.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464280818/d25cc856-0178-4d94-9f56-654f4c62637d.png" alt="No Closure with Global Output" width="2560" height="1440" loading="lazy"></p>
<p>If you add another variable:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> num3 = <span class="hljs-number">5</span>;
</code></pre>
<p>This <code>num3</code> isn't used by the <code>sum</code> function, but if you look in the global scope, you can still see it. The browser shows <code>num3</code> as well.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464328789/6bcffff2-3e8c-4cc7-8da6-9f03910aee92.png" alt="Global Scope with num3 Output" width="2560" height="1440" loading="lazy"></p>
<p>But a closure only keeps what's necessary. Here, <code>num3</code> exists because it's part of the global scope. The global object always holds references to its own variables, which is why <code>num3</code> is visible. This often causes confusion: should you call it a closure or not?</p>
<p>The point is, in the 2016 documentation, the term "enclosing scope" was clearly mentioned. In the current documentation, that phrase is missing. This means they've intentionally avoided that confusion.</p>
<p>The modern definition now says, "closure is the combination of a function bundled together with references to its surrounding state" which is written more concisely compared to before. (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">Reference</a>)</p>
<p>Here, "state" refers to the lexical environment – that could be the child's environment, the parent's environment, or the entire scope. Based on this definition, a function keeps itself along with any variables it needs to remember, all bundled together. Explaining this clearly in words can be tricky. But you'll see more examples ahead, which will make each use case clear.</p>
<h2 id="heading-practical-example-self-contained-closures">Practical Example: Self-Contained Closures</h2>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
    <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> num1 + num2;
    }

    <span class="hljs-built_in">console</span>.log(sum());
    <span class="hljs-built_in">console</span>.dir(sum);
})();
</code></pre>
<p>Let's look at another aspect. You're going back to the IIFE function. Here, you have a function called <code>sum</code> that adds <code>num1</code> and <code>num2</code> and returns the result. Both <code>num1</code> and <code>num2</code> exist inside the IIFE function. This means you've kept the whole setup self-contained within a closure function.</p>
<p>When you call the <code>sum</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(sum());
</code></pre>
<p>and on the next line write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(sum);
</code></pre>
<p>Check the output. Initially, <code>2 + 3</code> gives <code>5</code>, which is exactly what you see. Since <code>num1</code> and <code>num2</code> now exist inside the global scope of the IIFE.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464361079/cdcff658-023c-4a25-8749-eb618b3cfcc3.png" alt="IIFE Closure Output" width="2560" height="1440" loading="lazy"></p>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
    <span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> num1 + num2;
    }
    <span class="hljs-built_in">console</span>.log(sum());
    <span class="hljs-built_in">console</span>.dir(sum);

    num1 = <span class="hljs-number">6</span>;
    num2 = <span class="hljs-number">7</span>;

    <span class="hljs-built_in">console</span>.log(sum());
    <span class="hljs-built_in">console</span>.dir(sum);
})();
</code></pre>
<p>You can modify these variables if you want:</p>
<pre><code class="lang-javascript">num1 = <span class="hljs-number">6</span>;
num2 = <span class="hljs-number">7</span>;
</code></pre>
<p>Then if you call again:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(sum());
<span class="hljs-built_in">console</span>.dir(sum);
</code></pre>
<p>You'll see two different results. The first call returns <code>5</code> because initially <code>2 + 3</code> was calculated. After changing <code>num1</code> and <code>num2</code>, the next call returns <code>13</code>. So, you can see that a closure keeps hold of the outer variables and makes them accessible inside the function, right?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464386404/cd2447c8-447e-4fff-b72d-f6ec2d2c8122.png" alt="IIFE Closure with Updated Values Output" width="2560" height="1440" loading="lazy"></p>
<p>Now, at that moment, you checked the function using <code>console.dir</code>. First, expand the <code>dir</code> at the bottom. Here, you see an entry labeled "closure," and inside it, you notice <code>num1 = 6</code> and <code>num2 = 7</code>. Great, because before writing <code>dir</code>, you had changed the values of <code>num1</code> and <code>num2</code>, so it's showing the latest values. But if you go back to the previous state and expand the first <code>console.dir</code>, surprisingly, it still shows <code>num1 = 6</code> and <code>num2 = 7</code>. Both are the same – pretty weird, isn't it?</p>
<p>This is because when you did <code>console.log</code>, the result showed <code>2 + 3</code>. But in the very next line, the values hadn't actually changed yet. In <code>console.dir</code>, you see that inside the closure, the values remain 6 and 7.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464426043/f7f87ffb-8bf5-4fbb-ac1c-091bee65570c.gif" alt="Closure with Updated Values Dir Output" width="1138" height="640" loading="lazy"></p>
<p>This is exactly what I’ve been emphasizing: <strong>a closure doesn't really hold the values themselves. It holds a reference to the variables.</strong></p>
<h3 id="heading-understanding-references">Understanding References</h3>
<p>So, what does this mean? It means that there's a pointer stored to the memory location of your variable. Once a reference is stored, the pointer itself stays the same, but the value can change anytime.</p>
<p>When you use <code>console.dir</code>, the browser is showing that reference, which is why it always displays the latest value. The browser works very fast, and the reference has already been updated. When you set <code>num1</code> and <code>num2</code> to 6 and 7 inside the closure, the reference gets updated. You're seeing the exact same variable, but you don't see the intermediate values. But when you do <code>console.log</code>, the function uses its corresponding value correctly. That's why not every change in the intermediate scope is clearly visible. Because of reference updates, you always see the latest value, not the direct intermediate state.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464448552/b61bc77c-2563-4fb0-9630-d36a4f304439.png" alt="Closure Reference Output" width="2560" height="1440" loading="lazy"></p>
<p>So, to reiterate: a closure doesn't store the actual values inside. It stores references to those values.</p>
<p>Keeping this concept in mind is really crucial.</p>
<h2 id="heading-the-difference-between-var-and-let">The Difference Between <code>var</code> and <code>let</code></h2>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
<span class="hljs-keyword">var</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">var</span> num2 = <span class="hljs-number">3</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-built_in">console</span>.dir(sum);
</code></pre>
<p>Now, let's look at another aspect of closures. Earlier, you declared two variables in the global scope: <code>num1</code> and <code>num2</code>. So far, you've been using the <code>var</code> keyword. If you don't put anything inside an IIFE and just stay in the global scope, you won't see any closure in the browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464484448/99a70a30-f07f-469d-a592-59f3ed5f193c.png" alt="No Closure In Global Output" width="2560" height="1440" loading="lazy"></p>
<p>But where do <code>num1</code> and <code>num2</code> live? Well, in the global scope. That's why you write <code>console.dir(sum)</code>. In the browser, you can see <code>num1</code> and <code>num2</code> inside the global object.</p>
<p>Here's the interesting part: what happens if you replace these <code>var</code> keywords with <code>let</code>?</p>
<h3 id="heading-understanding-var-and-let-scoping">Understanding <code>var</code> and <code>let</code> Scoping</h3>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
<span class="hljs-keyword">let</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> num2 = <span class="hljs-number">3</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-built_in">console</span>.log(sum());

<span class="hljs-built_in">console</span>.dir(sum);
</code></pre>
<p>This is where the difference between <code>var</code> and <code>let</code> comes in. Many people think they're the same, but in JavaScript, <code>var</code> and <code>let</code> are not equal.</p>
<p>Simply put:</p>
<ul>
<li><p><code>var</code> is the old JavaScript declaration, and it's function-scoped. A variable declared with <code>var</code> only lives inside the function it's defined in. If it's defined outside any function, it goes to the global scope.</p>
</li>
<li><p><code>let</code> is the new ES6 declaration, and it's block-scoped. A variable declared with <code>let</code> only exists within the block or scope where it was defined and cannot be accessed from outside.</p>
</li>
</ul>
<p>One important difference is hoisting. Variables declared with <code>var</code> are hoisted, meaning JavaScript moves the declaration to the top, but the initialization doesn't happen. So if you use a <code>var</code> before it's declared, you'll get <code>undefined</code>. With <code>let</code>, even though it's hoisted, the <a target="_blank" href="https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/">temporal dead zone</a> ensures that using it before declaration throws an error.</p>
<h3 id="heading-observing-the-difference">Observing the Difference</h3>
<p>Let's see what happens if you declare the variable with <code>let</code>. Last time, when it was just in the global scope, you could see the variables when you did <code>console.dir</code>. Now, though, you see a new object named <code>script</code> has appeared, and <code>num1</code> and <code>num2</code> are no longer in the global scope.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464511845/d627b15b-8d03-48e2-ae11-3e3516cc760e.png" alt="Let Scope Output" width="2880" height="1800" loading="lazy"></p>
<p>Why is that? It's because of the difference between <code>let</code> and <code>var</code> that you talked about earlier. <code>let</code> is block-scoped, while <code>var</code> is function-scoped. If you treat the outer context as a main function, a variable declared with <code>var</code> becomes part of the global scope. But with <code>let</code>, it stays within its block scope and doesn't directly become part of the global object. So <code>let</code> actually lives inside a separate object called <code>script</code> and not in the global scope.</p>
<p>Understanding this is really important, because if you’re following along with this handbook and you’re trying to print variables while using <code>let</code> out of habit, the output won't be like it is with <code>var</code>. This can definitely be confusing. Simply put, <code>let</code> doesn't go into the global object. It exists inside a separate <code>script</code> object.</p>
<h3 id="heading-using-iife-with-let">Using IIFE with <code>let</code></h3>
<p><strong>Full code:</strong> <code>example-3.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-3.js</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> num1 = <span class="hljs-number">2</span>;
    <span class="hljs-keyword">let</span> num2 = <span class="hljs-number">3</span>;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> num1 + num2;
    }

    <span class="hljs-built_in">console</span>.dir(sum);
})();
</code></pre>
<p>But what if you wrap the whole thing in an enclosing function again, like before with an IIFE? When you check the output now, everything goes back inside its closure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464534468/13f0579b-0476-47b4-a4b3-2d894b0e1570.png" alt="Closure with Let in IIFE Output" width="2560" height="1440" loading="lazy"></p>
<p>Ultimately, the concept of closures remains the same: what changes is whether the variable goes into <code>var</code> or <code>let</code> scope.</p>
<p>Now the situation becomes a bit simpler. You have a function, and it's in its end-closing state. According to the definition of a closure, the inner function of this function is using the outer variable <code>num1</code>. So, this inner function definitely needs a closure. That closure comes from exactly this function.</p>
<p>JavaScript creates the closure and packages <code>num1</code> inside it. The outer global world always exists separately, of course. Also remember, when using <code>console.dir</code> in the browser, the output will look different depending on whether you're dealing with <code>let</code> or <code>var</code>.</p>
<h2 id="heading-understanding-closures-through-a-practical-stopwatch-example">Understanding Closures Through a Practical Stopwatch Example</h2>
<p>So far, all the examples you've seen were very simple. Now, let's look at a practical example that will help you understand closures better and clear up any confusion.</p>
<p><strong>Full code:</strong> <code>example-4.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-4.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stopWatch</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> startTime = <span class="hljs-built_in">Date</span>.now();

    <span class="hljs-keyword">var</span> getDelay = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Date</span>.now() - startTime);
    };
    <span class="hljs-keyword">return</span> getDelay;
}

<span class="hljs-keyword">var</span> timer = stopWatch();

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100000000</span>; i++) {
    <span class="hljs-keyword">var</span> a = <span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">1000000</span>;
}

timer();
</code></pre>
<h3 id="heading-defining-the-stopwatch-function">Defining the Stopwatch Function</h3>
<p>Let's define a function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stopWatch</span>(<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>You've named it <code>stopWatch</code>, and it works just like a real stopwatch. Just like when you start a stopwatch, wait for a while, and then stop it to get the elapsed time, this function will do the same.</p>
<p>First, write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> startTime = <span class="hljs-built_in">Date</span>.now();
</code></pre>
<p>This stores the current time in <code>startTime</code>. Then, inside the function, define:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> getDelay = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{};
</code></pre>
<p>Create a <code>getDelay</code> function, which will log the elapsed time to the console. For that, write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Date</span>.now() - startTime);
</code></pre>
<p>Here, the elapsed time is calculated by subtracting <code>startTime</code> from the current time. Finally, simply return this <code>getDelay</code> function. The <code>stopWatch</code> function does just one thing: when you call <code>stopWatch</code>, it starts a stopwatch using <code>Date.now()</code> and returns a <code>getDelay</code> function. When you call that <code>getDelay</code> function, it shows the elapsed time from the start time to the current moment.</p>
<h3 id="heading-using-the-stopwatch">Using the Stopwatch</h3>
<p>Now, call it. Write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> timer = stopWatch();
</code></pre>
<p>Here, you've started the <code>stopWatch</code>. This function executes, which means <code>startTime</code> is set and the <code>getDelay</code> function is defined. Then, <code>stopWatch</code> returns that <code>getDelay</code> function. The <code>stopWatch</code> function itself isn't called directly afterward – you simply called it once, and the outer function returns the <code>getDelay</code> function. Store this returned function in <code>timer</code>.</p>
<p>At this point, the <code>stopWatch</code> is already running because you called it, but you haven't printed anything from <code>getDelay</code> yet. Before calling <code>getDelay</code>, create a fake delay like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100000000</span>; i++) {}
</code></pre>
<p>Use a large for-loop to waste some time. You chose a big number intentionally so it takes a noticeable delay. If you want, you can also perform some expensive operations in the loop, like calculating a random number:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">1000000</span>;
</code></pre>
<p>This way, you create a fake delay.</p>
<h3 id="heading-calling-the-timer-function">Calling the Timer Function</h3>
<p>Now, we come to <code>timer</code>. <code>Timer</code> is actually a function because it was returned by calling <code>stopWatch</code>. This returned <code>getDelay</code> function acts as your actual timer. Let’s call <code>timer()</code> and see what happens. The output doesn't appear instantly – it takes a moment, and then it shows up. So you get a delay.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464566077/f4a450a5-796b-4999-97cb-1e697afbbcfa.gif" alt="Stopwatch Output" width="1138" height="640" loading="lazy"></p>
<p>The question is: how is this still working? The <code>stopWatch</code> function, where you initially called it, has already finished executing. That means everything inside that function should be gone.</p>
<p>So how does <code>timer()</code> still know the value of <code>startTime</code>? Especially after you added such a long delay before calling it? This means the <code>timer</code> function still remembers its parent function – specifically, the <code>startTime</code> variable inside <code>stopWatch</code>. It holds onto that reference.</p>
<p>How? Because of a closure. When <code>getDelay</code> was created, a closure was also created inside it that kept track of the <code>startTime</code> variable. So even after the delay, and even after a long time, it can still use that old value. This shows that JavaScript is really smart. It tracks all variables, references, and closures, and when needed, it can use them again. This is why this behavior is possible: because of closures.</p>
<h3 id="heading-inspecting-the-timer-function">Inspecting the Timer Function</h3>
<p><strong>Full code:</strong> <code>example-4.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-4.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stopWatch</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> startTime = <span class="hljs-built_in">Date</span>.now();
    <span class="hljs-keyword">var</span> getDelay = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Date</span>.now() - startTime);
    };
    <span class="hljs-keyword">return</span> getDelay;
}

<span class="hljs-keyword">var</span> timer = stopWatch();

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100000000</span>; i++) {
    <span class="hljs-keyword">var</span> a = <span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">1000000</span>;
}

timer();

<span class="hljs-built_in">console</span>.dir(timer);
</code></pre>
<p>If you do:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(timer);
</code></pre>
<p>like before and check the output in the browser, you'll notice it takes some time to appear because of the delay. But even after the delay, it still retains <code>startTime</code> inside the closure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464588970/1dcb2502-4989-447f-9c4c-09056c948243.png" alt="Timer Closure Output" width="2560" height="1440" loading="lazy"></p>
<p>If you try:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(startTime);
</code></pre>
<p>you won't be able to access <code>startTime</code> directly. But since <code>timer</code> is a member function, it can use that <code>startTime</code> you initialized long ago, before the for-loop. It still remembers <code>startTime</code>. No matter how long the delay, it can keep track. Even if there were more lines of code or more expensive operations during the delay, at the end of the day, when you call the timer, the closure ensures that <code>startTime</code> is correctly preserved.</p>
<p>This is one of the more fascinating aspects of JavaScript: it can really remember such information, and this is one of the biggest use cases of closures.</p>
<h3 id="heading-closures-and-garbage-collection">Closures and Garbage Collection</h3>
<p>This is one of the most powerful features of closures. Because of closures, no matter how many times you call the <code>timer()</code> function, each call works independently and keeps its own reference. Every time, a new reference is created and held as long as it's needed.</p>
<p>Let's consider a small example – but imagine in a large application, there could be countless closures holding references to many variables. Naturally, the question arises: if so many things are being remembered, will performance suffer?</p>
<p>This is where JavaScript's performance optimization comes in. <strong>JavaScript is a smart, garbage-collected language.</strong> That means when JavaScript realizes that a reference or variable is no longer needed, it automatically removes it from memory.</p>
<p>In some situations, programmers can manually optimize. For example, if you created a timer holding a reference to a <code>getDelay()</code> function, but you haven't called <code>getDelay()</code> yet, JavaScript doesn't know if it will be used in the future, so it keeps the reference.</p>
<p><strong>Full code:</strong> <code>example-4.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-4.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stopWatch</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> startTime = <span class="hljs-built_in">Date</span>.now();

    <span class="hljs-keyword">var</span> getDelay = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Date</span>.now() - startTime);
    };
    <span class="hljs-keyword">return</span> getDelay;
}

<span class="hljs-keyword">var</span> timer = stopWatch();

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100000000</span>; i++) {
    <span class="hljs-keyword">var</span> a = <span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">1000000</span>;
}

timer();

<span class="hljs-built_in">console</span>.dir(timer);
timer = <span class="hljs-literal">null</span>;

timer();
</code></pre>
<p>If you're certain it won't be used anymore, you can manually clear the reference by writing:</p>
<pre><code class="lang-javascript">timer = <span class="hljs-literal">null</span>;
</code></pre>
<p>Now, <code>timer()</code> won't work because you set it to null. JavaScript understands that it's no longer needed and garbage collects the reference from memory. If you try this in the browser, you'll see an error: "TypeError: timer is not a function" – because <code>timer</code> is now null.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464662207/267dbda0-31c0-47b3-9df8-a6b18c04b317.png" alt="Timer Null Error Output" width="2560" height="1440" loading="lazy"></p>
<p>Simply put, setting <code>timer = null</code> tells JavaScript, "This variable won't be used anymore, forget it." The Garbage Collector then recognizes that there are no references and quietly removes it from memory, preventing memory waste.</p>
<p>The interesting part is that JavaScript doesn't just run the code – it predicts a lot even before compilation. When it sees <code>timer = null</code>, it already knows, "Okay, the programmer used this timer only this much, and it won't be needed anymore." So as soon as the code finishes running, it intelligently cleans up the memory.</p>
<p>This makes your program automatically optimized. There are no memory leaks, browser load decreases, and JavaScript executes faster. This is a very small example, but it already shows how elegantly you can manage performance in JavaScript.</p>
<h2 id="heading-closures-in-asynchronous-code">Closures in Asynchronous Code</h2>
<p>So far, all the examples you've seen were using closures in a synchronous way. Now, many people might wonder, "Okay, but how do closures work in asynchronous situations?"</p>
<p>That's a very good question. In real-world coding, most tasks run asynchronously – like with <code>setTimeout</code>, <code>fetch</code>, or event listener functions. The key point is, synchronous code executes line by line, but asynchronous code takes some time to complete. That means you call a function, but its result arrives a little later.</p>
<p>So the question is: if the outer scope has already finished by then, how does the inner function still remember the values of the outer variables?</p>
<p><strong>This is exactly where the true power of closures comes in.</strong> A closure keeps the reference to the outer scope as long as the inner function hasn't executed yet. That means whether the code is synchronous or asynchronous, closures work the same way.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464732632/3d49dab4-4b0e-4f58-9923-fe5dae876915.gif" alt="Asynchronous Closures" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-basic-asynchronous-example-with-settimeout">Basic Asynchronous Example with <code>setTimeout</code></h3>
<p><strong>Full code:</strong> <code>example-5.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-5.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncExample</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;

    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(a);
    }, <span class="hljs-number">3000</span>);
}

asyncExample();
</code></pre>
<p>Now let’s see a small asynchronous example to understand how closures work and why they are just as reliable in asynchronous scenarios.</p>
<p>Define a function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncExample</span>(<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>Inside this function, write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;
</code></pre>
<p>You've defined a variable. Next, use JavaScript's built-in <code>setTimeout</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{});
</code></pre>
<p><code>setTimeout</code> takes two parameters: one is the function to run, and the other is the time in milliseconds, meaning it will call that function after the specified delay.</p>
<p>Now, suppose you put <code>console.log(a)</code> inside that function. Surprisingly, even though <code>a</code> isn't defined inside the timeout function, it can still access the <code>a</code> from <code>asyncExample</code>'s outer scope. This is possible because of closures. After 3 seconds, it appears, and you see <code>20</code>. This is also possible because of closures. The function inside <code>setTimeout</code> doesn't have <code>a</code> defined within itself, yet it can access <code>a</code> from <code>asyncExample</code>'s scope.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464763043/0d51130c-3299-49c1-bab9-6cac74b215ab.png" alt="Asynchronous Closure Output" width="2560" height="1440" loading="lazy"></p>
<h3 id="heading-external-function-reference-example">External Function Reference Example</h3>
<p><strong>Full code:</strong> <code>example-5.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-5.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncExample</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(a);
    }

    <span class="hljs-built_in">setTimeout</span>(myFunc, <span class="hljs-number">3000</span>);
    <span class="hljs-built_in">console</span>.dir(myFunc);
}

asyncExample();
</code></pre>
<p>Now, what if you define the <code>setTimeout</code> function outside <code>asyncExample</code>, just for demonstration – like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>Inside <code>myFunc</code>, write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(a);
</code></pre>
<p>Then pass <code>myFunc</code> into <code>setTimeout</code> and also write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(myFunc);
</code></pre>
<p>If you check the output of <code>console.dir</code>, you'll see that inside <code>myFunc</code>, the closure contains the variable <code>a=20</code>. This is because <code>a</code> was part of <code>asyncExample</code>'s scope, so <code>myFunc</code> can still access it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464809847/359fc698-cc18-4e41-beb7-e3b7148accc1.png" alt="Asynchronous Closure with External Function Output" width="2560" height="1440" loading="lazy"></p>
<p>Just like before, this is possible thanks to closures. But here, there's a subtle difference. Earlier, you talked about a reference example, but this reference works a little differently.</p>
<p><strong>Full code:</strong> <code>example-5.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-5.js</span>

<span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncExample</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(a);
    }

    <span class="hljs-built_in">setTimeout</span>(myFunc, <span class="hljs-number">3000</span>);
    <span class="hljs-built_in">console</span>.dir(myFunc);
}

asyncExample();

a = <span class="hljs-number">30</span>;
</code></pre>
<p>Suppose the variable <code>a=20</code> was originally inside <code>asyncExample</code>. Now, if you move <code>a</code> to the global scope and write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;
</code></pre>
<p>In simple terms, you've defined it outside. Now, the closure won't show it, because it's part of the global scope. <code>a</code> will just exist in the global scope with a value of <code>20</code>. You call the <code>asyncExample</code> function, which starts the <code>setTimeout</code> timer. Then, on the next line after calling <code>asyncExample</code>, you change the value of <code>a</code>:</p>
<pre><code class="lang-javascript">a = <span class="hljs-number">30</span>;
</code></pre>
<p>Now think: if <code>myFunc</code> is called as the callback for <code>setTimeout</code> and does <code>console.log(a)</code>, what value will it show? If you check the output, it will show <code>30</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464836227/3d4cc9aa-cd26-4026-bc14-2d0b980bc333.png" alt="Global Variable Asynchronous Closure Output" width="2560" height="1440" loading="lazy"></p>
<p>What does this mean?</p>
<p>When <code>asyncExample</code> is called, the <code>setTimeout</code> starts and <code>myFunc</code> is ready as the callback. Inside <code>myFunc</code>, you have <code>console.log(a)</code>. At that moment, <code>a</code> was <code>20</code> in its parent scope. But since <code>a</code> is now global and its value has been changed from outside, when the callback executes, it shows <code>30</code>.</p>
<p>This demonstrates that <strong>closures actually hold a reference to the variable.</strong> If the variable is global, any external changes are also tracked. So if you expand the global <code>a</code> in the console, you'll see <code>a = 30</code>.</p>
<p>I mentioned earlier that closures keep a reference to the value. So when <code>setTimeout</code> sends the callback to the main thread after 3 seconds, <code>myFunc</code> can still access that reference. Remember, <code>myFunc</code> comes back via <code>setTimeout</code> from another place – it doesn't run directly on the main thread. This is part of asynchronous JavaScript.</p>
<p>The function is called in the main thread after returning from the Web API, but it still retains the reference to <code>a</code>. Since <code>a</code> has been changed globally, when <code>myFunc</code> prints it, it shows the new value <code>30</code>.</p>
<p>This point is very important. Practicing multiple examples will help you better understand how closures track outer variables in asynchronous situations. This is why you need to be careful when using global variables and <code>var</code>.</p>
<p>This is also the reason <code>var</code> can sometimes cause conflicts, and why the <code>let</code> keyword was introduced. For example, if you define <code>var a</code> globally and later change <code>a</code> somewhere in the program, any asynchronous functions referencing <code>a</code> will use the new value. That's why using <code>var</code> with <code>setTimeout</code> or other asynchronous functions can lead to such issues.</p>
<p>💡An important point is that a closure doesn't keep the entire variable from its parent scope. It only keeps a reference to that variable.</p>
<h2 id="heading-practical-example-api-requests-with-closures">Practical Example: API Requests with Closures</h2>
<p>Now, let’s see another practical example of closures. In typical JavaScript applications, you often make AJAX requests to fetch data from an API URL. We’ll see how closures are used in this context. For API requests like this, JavaScript's built-in <code>fetch</code> function can be used, though third-party libraries like <code>axios</code> or <code>jQuery AJAX</code> can also accomplish the same task.</p>
<p><strong>Full code:</strong> <code>example-6.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-6.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">apiFunction</span>(<span class="hljs-params">url</span>) </span>{
    fetch(url).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(res);
    });
}

apiFunction(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos/1"</span>);
</code></pre>
<p>Here, we’ll use <code>fetch</code> for a practical example. First, write a function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">apiFunction</span>(<span class="hljs-params">url</span>) </span>{}
</code></pre>
<p>You've named it <code>apiFunction</code> and gave it a parameter called <code>url</code>. This function will send a request to that URL. Then you call the built-in <code>fetch</code> function:</p>
<pre><code class="lang-javascript">fetch(url);
</code></pre>
<p>So what does <code>fetch</code> do with the URL? Basically, <code>fetch</code> returns a promise. You know that to get the output from a promise, you use <code>then</code>. So you write:</p>
<pre><code class="lang-javascript">.then(<span class="hljs-function">(<span class="hljs-params">res</span>)=&gt;</span>{})
</code></pre>
<p>After the response comes back, you use a callback function. Here, you log the response to the console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(res);
</code></pre>
<p>This is how your <code>apiFunction</code> is set up.</p>
<p>Now call the function. You need to pass a URL for the API call. A popular choice is <a target="_blank" href="https://jsonplaceholder.typicode.com/">jsonplaceholder</a>, so use its <code>/todos/1</code> endpoint:</p>
<pre><code class="lang-javascript">apiFunction(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos/1"</span>);
</code></pre>
<p>Check the output. Notice that it appears after a short delay-this is asynchronous.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464859727/39dd7757-f04e-49f2-ac8a-46f2472a429e.png" alt="API Function Output" width="2560" height="1440" loading="lazy"></p>
<p>To make this clearer, write another line below:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I am here"</span>);
</code></pre>
<p>Now the question is: which prints first? Without a doubt, "I am here" prints first, and then the output from <code>apiFunction</code> appears. This clearly demonstrates the flow of asynchronous operations. Since the response comes quickly, it might not have been obvious without this extra line.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464881162/59208d49-83f9-48af-8ab4-c9d1c453356b.png" alt="API Function with Log Output" width="2560" height="1440" loading="lazy"></p>
<p>What does this mean? The output is coming, right? Here, the connection to closures is that you passed the <code>url</code> parameter from outside when calling <code>apiFunction</code>. This <code>url</code> now exists inside the body of <code>apiFunction</code>. <code>fetch</code> takes it as a parameter, and then the callback function inside <code>then</code> executes much later.</p>
<p>By that time, the call to <code>apiFunction</code> has already finished, but the callback still remembers the variables from its scope. That's why even after the result arrives, you can still access <code>url</code>. To see this, print it:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(url);
</code></pre>
<p>Notice that the output is correct. This means that if there were more nested functions inside <code>then</code>, like another <code>then</code> inside a <code>then</code>, all the way down, the innermost function could still access the original <code>url</code>. And this is possible only because of closures.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464901905/8980f4a3-3eb9-4af1-868f-d3ef6d907e9b.png" alt="API Function URL Output" width="2560" height="1440" loading="lazy"></p>
<h3 id="heading-refactoring-with-external-function">Refactoring with External Function</h3>
<p><strong>Full code:</strong> <code>example-6.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-6.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">apiFunction</span>(<span class="hljs-params">url</span>) </span>{
    handleResponse = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">res</span>) </span>{
        <span class="hljs-built_in">console</span>.log(res);
        <span class="hljs-built_in">console</span>.log(url);
    };

    fetch(url).then(handleResponse);
    <span class="hljs-built_in">console</span>.dir(handleResponse);
}

apiFunction(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos/1"</span>);
</code></pre>
<p>To demonstrate, let’s rewrite the callback function inside <code>apiFunction</code> a little differently:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleResponse</span>(<span class="hljs-params">res</span>) </span>{}
</code></pre>
<p>This function simply does <code>console.log(url)</code>. Now pass <code>handleResponse</code> into the <code>then</code>. Then write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(handleResponse);
</code></pre>
<p>In the output, you'll see that inside <code>handleResponse</code>, the closure contains <code>url</code>. This is because it was part of <code>apiFunction</code>'s scope, so it can access it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464922631/3a2edbeb-d3e9-470d-bea3-fdf46144165e.png" alt="API Function with External Handler Output" width="2560" height="1440" loading="lazy"></p>
<h2 id="heading-advanced-example-closures-in-loops">Advanced Example - Closures in Loops</h2>
<p>Finally, let’s look at another example that often comes up in job interviews. This one is a bit more complex and tricky, and it shows how using closures inside loops can create unpredictable output.</p>
<h3 id="heading-synchronous-loop-example">Synchronous Loop Example</h3>
<p><strong>Full code:</strong> <code>example-7.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }
    a();
}
</code></pre>
<p>Let’s write a simple for loop:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {}
</code></pre>
<p>This loop will run three times, and inside it we’ll define another function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>Inside this function, you simply do:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(i);
</code></pre>
<p>From this, you see that the function <code>a</code> exists within the scope of the <code>for loop</code>, but in reality, it's also accessible in the global scope. Then you call the function <code>a</code>:</p>
<pre><code class="lang-javascript">a();
</code></pre>
<p>The expected output would be 0, 1, 2. First, the value of <code>i</code> prints 0, then 1, then 2 – one after another. Looking at the output, you see 0, 1, 2. This is because you defined <code>i</code> using <code>let</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763464949327/23ded10a-19c2-4aff-9d11-927e179c2c82.png" alt="Synchronous Loop Output" width="2560" height="1440" loading="lazy"></p>
<p><strong>Full code:</strong> <code>example-7.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }
    a();
}
</code></pre>
<p>If you remove <code>let</code> and use <code>var</code> instead, what happens? Even with <code>var</code>, the output will be the same in this simple case because <code>var</code> works outside the block scope. Writing <code>for (var i = 0)</code> or declaring <code>var i</code> separately behaves effectively the same.</p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-keyword">var</span> i;
<span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }
    a();
}
</code></pre>
<p>So in this case, there's no problem. A closure isn't required because you are running the function in the global scope. Your <code>i</code> prints 0, then 1, then 2, and everything works correctly.</p>
<h3 id="heading-asynchronous-loop-example">Asynchronous Loop Example</h3>
<p><strong>Full code:</strong> <code>example-7.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }, <span class="hljs-number">1000</span> * i);
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After for loop"</span>);
</code></pre>
<p>Now let's go back and use <code>let</code> for <code>i</code> again. Suppose you want to call the <code>a</code> function from outside the loop. Imagine you wrap the function call in a <code>setTimeout</code>, and in the first parameter you pass the body of <code>a</code> as a callback, while the second parameter is <code>1000 * i</code> milliseconds.</p>
<p>Using this <code>1000 * i</code>, you want 0 to print after 1 second, 1 after 2 seconds, and 2 after 3 seconds. When you run this, the output comes exactly as expected: after 1 second, 0 prints; after 2 seconds, 1 prints; and after 3 seconds, 2 prints.</p>
<p>But here's the important point: the <code>for</code> loop itself is synchronous, while the functions inside <code>setTimeout</code> are asynchronous. That means the functions inside <code>setTimeout</code> will execute one by one according to the timer, only after the loop has finished. First after 1 second, then after 2, and then after 3.</p>
<p>You can verify this asynchronous behavior. Suppose at the end of the loop you write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After for loop"</span>);
</code></pre>
<p>Now, if you check the output, "After for loop" prints first, then after 1 second, 0 prints, after 2 seconds, 1 prints, and finally 2 prints. This clearly shows how asynchronous functions execute, right? No confusion there.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465056351/9ca676db-c54a-4dc2-9ac8-0bbf1cf08be4.gif" alt="Asynchronous Loop Output" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-the-var-vs-let-problem">The <code>var</code> vs <code>let</code> Problem</h3>
<p><strong>Full code:</strong> <code>example-7.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }, <span class="hljs-number">1000</span> * i);
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After for loop"</span>);
</code></pre>
<p>Now, let's see what happens if you replace <code>let i</code> with <code>var i</code>. The interesting part is, if you use "var i" instead of "let i", the behavior changes. All three outputs end up being 3. You don't get 0, 1, 2 like before. That's exactly the tricky part of this question.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465090022/87518cc5-4942-4c2e-a728-a11751d9a552.png" alt="Var Loop Problem Output" width="2560" height="1440" loading="lazy"></p>
<p>This question often comes up in job interviews because it's a bit advanced, but if you understand closures and the difference between <code>let</code> and <code>var</code> scopes, it's not complicated at all. You can analyze this by going back to <code>let</code>. Remove <code>var</code> and write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;
</code></pre>
<p>Now the expected output is 0, 1, 2. <code>let</code> is block-scoped, meaning this <code>i</code> exists only inside the loop and has no effect outside.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465164777/ba0b0084-95db-4de5-a1e6-67aaa8172c51.gif" alt="Let Loop Output" width="1138" height="640" loading="lazy"></p>
<p>During the first iteration, <code>i</code> is 0, and the <code>setTimeout</code> function is defined. This function will be called after the loop finishes, so a closure is used to remember the value of i. The callback needs a closure to reference i correctly. Since <code>let</code> doesn't leak outside the loop, each iteration creates a new i. For example, when i becomes 1, it's a completely separate <code>i</code> from the previous iteration.</p>
<p><strong>Full code:</strong> <code>example-7.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-keyword">var</span> i;

<span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }, <span class="hljs-number">1000</span> * i);
}
<span class="hljs-built_in">console</span>.log(i);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After for loop"</span>);
</code></pre>
<p>So, when this function runs the second time, it references this new i. But with <code>var</code>, the situation is different. <code>var</code> is function-scoped, so the same variable exists outside the loop. If you write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> i;
</code></pre>
<p>and then use the loop:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {}
</code></pre>
<p>there is only one i. Changing i inside the loop modifies the same i – no new i is created. So when the setTimeout callbacks execute, they all reference that same i. From previous examples, you know setTimeout callbacks run after the loop finishes. Now, after the loop ends, what's the value of i? Since you used <code>var</code>, i has become 3.</p>
<p>Check it with:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(i);
</code></pre>
<p>In the console, you'll see 3 prints first. That means that when the callbacks execute, they all reference the same i, which is already 3.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465201159/7730557a-5255-4c32-8f46-ca01c11a6899.png" alt="Var Loop Problem with Log Output" width="2560" height="1440" loading="lazy"></p>
<p>So every console.log in the callbacks prints i = 3, which explains the output perfectly.</p>
<h3 id="heading-using-consoledir-with-loop-closures">Using <code>console.dir</code> with Loop Closures</h3>
<p><strong>Full code:</strong> <code>example-7.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-comment">// var i;</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }

    <span class="hljs-built_in">setTimeout</span>(myFunc, <span class="hljs-number">1000</span> * i);

    <span class="hljs-built_in">console</span>.dir(myFunc);
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After for loop"</span>);
</code></pre>
<p>To understand this even better, you can use "console.dir" like before.</p>
<p>Let's see how. First, you'll stick with the <code>let</code> case. So in the for loop you write:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;
</code></pre>
<p>You comment out the global "var i;" since <code>let</code> is block-scoped. Now let's see how the closure works. The closure is created inside the setTimeout callback function, and you want to inspect this callback function.</p>
<p>For that, you define:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>and pass this myFunc inside setTimeout. Then, to inspect it, write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(myFunc);
</code></pre>
<p>If you run this, the browser shows the same output. That means the dir of myFunc appears three times, but in Chrome's console, it only prints once. Chrome wraps similar objects together, so even though the internal properties are different, it doesn't display them separately. To see each property individually, take the next step.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465312812/f4ec260c-2b8f-474f-a1ad-59797eda63d4.gif" alt="Let Loop with Dir Output" width="1138" height="640" loading="lazy"></p>
<p>Below the dir, write:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"---"</span>);
</code></pre>
<p>This acts as a separator. Now, when the browser prints myFunc's dir, it also prints the separator, making it clear that each instance is separate.</p>
<p>At the same time, outside the for loop, add:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After for loop"</span>);
</code></pre>
<p>Now, if you check the output, the browser prints 'After for loop' first, then 0, 1, 2. When you defined it, the console logs show myFunc and the dashes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465334580/a92fd163-4095-4b6a-bdb5-f239350a7416.png" alt="Let Loop with Dir and Separator Output" width="2560" height="1440" loading="lazy"></p>
<p>Notice, when i is 0, the closure holds i = 0. When i = 1, the closure holds i = 1. When i = 2, the closure holds i = 2. So, all three values exist as references until the end, which is why you get three separate outputs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465373352/5e8903fa-76c4-4031-9a09-d45e9cd29e5f.gif" alt="Let Loop Closure Values Output" width="1138" height="640" loading="lazy"></p>
<h3 id="heading-the-var-loop-problem">The <code>var</code> Loop Problem</h3>
<p><strong>Full code:</strong> <code>example-7.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(i);
    }

    <span class="hljs-built_in">setTimeout</span>(myFunc, <span class="hljs-number">1000</span> * i);

    <span class="hljs-built_in">console</span>.dir(myFunc);

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"---"</span>);
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After for loop"</span>);

<span class="hljs-built_in">console</span>.log(i);
</code></pre>
<p>But what happens if you replace <code>"let i"</code> with <code>"var i"</code>? After printing <code>'After for loop'</code>, all three outputs show 3. How? When i is 0, there's no closure because var moves this variable to the global scope. Unlike the previous example, no closure is needed here. Var exists in the global scope, and i changes within that same global variable.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465417027/24635534-867e-4b9d-a4cf-637abbd4610c.png" alt="Var Loop with Dir Output" width="2560" height="1440" loading="lazy"></p>
<p>So, if you expand the first myFunc in the console and look for i in the global scope, you'll see i = 3. Why? Because the for loop finishes first, and at the end, i becomes 3. At the moment of <code>'After for loop'</code>, i is 3. If you do "console.log(i)" there, the browser prints 3. This means, when the reference values are called, they still use the reference to that i. Even if i changes later in the program, since the calls happen afterward, the reference values get the updated i.</p>
<p>That's why the first call shows 3, the second call shows 3, and the third call also shows 3. If you expand them all, you'll see i = 3 everywhere. This happens because no closure is used here; it's referencing the original i in the global scope, which keeps updating.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465457673/56530a97-5bd4-4f67-9311-77655b9638cb.gif" alt="Var Loop Closure Values Output" width="1138" height="640" loading="lazy"></p>
<p>The difference in scope between let and var is why the output changes completely.</p>
<h3 id="heading-fixing-the-var-loop-problem-with-iife">Fixing the <code>var</code> Loop Problem with IIFE</h3>
<p>To fix this var issue, you can create an IIFE inside the for loop. This IIFE will take one parameter: in this case, the value of your loop variable "i."</p>
<p><strong>Full code:</strong> <code>example-7.js</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// example-7.js</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
    (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">i</span>) </span>{
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">console</span>.log(i);
        }

        <span class="hljs-built_in">setTimeout</span>(myFunc, <span class="hljs-number">1000</span> * i);

        <span class="hljs-built_in">console</span>.dir(myFunc);

        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"---"</span>);
    })(i);
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After for loop"</span>);
</code></pre>
<p>You write the code. Inside the IIFE, you're passing a parameter named "i." Of course, you can name it anything you want – you already know that. But for now, just keep it as "i." Then, when you call the IIFE, pass the loop's "i" value into it. Nice, right?</p>
<p>Let's see what the output looks like. This time, you get 0, 1, and 2 correctly. So, why is it fixed now? Because "i" is now inside its own scope within the IIFE. Whenever you pass "i" to myFunc, a separate copy of that "i" is created as a parameter inside myFunc, and that copy is what gets used inside the function.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465482476/0939504b-40c4-4b9c-b698-a55f266f24c4.gif" alt="IIFE Loop with Dir Output" width="1138" height="640" loading="lazy"></p>
<p>Everything's clear now, right? If you expand the dirs at the end, you'll see: the last one has "i = 2" in its closure, the second one has "i = 1," and the first one has "i = 0." Perfectly clear, isn't it?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1763465516842/0c708a0d-f0c6-44de-828e-61827375ecc1.gif" alt="IIFE Loop Closure Values Output" width="1138" height="640" loading="lazy"></p>
<h2 id="heading-summary-and-key-takeaways">Summary and Key Takeaways</h2>
<p>If you have a solid grasp of the overall concepts discussed here, and if you practice all these examples repeatedly, your understanding of closures will become much stronger.</p>
<p>Of course, there are more complex examples of closures, but the basics we've covered today are the most important. Once you understand them step by step, you'll be able to create many use cases yourself and debugging will no longer be difficult. Because now, with just a glance at <code>console.dir()</code> or by playing with the code a bit, you can see how closures actually work.</p>
<p>Not having a good understanding of closures can make you get stuck in many parts of JavaScript, especially when working with asynchronous code.</p>
<h3 id="heading-to-summarize">To summarize:</h3>
<p>If you're asked in a job interview, "What is a Closure?" you can answer simply:</p>
<blockquote>
<p>A closure is a mechanism where a function remembers variables outside its own scope and can access them whenever needed.</p>
</blockquote>
<p>In other words, values that aren't inside the function itself, but the function takes a reference from its parent or outer scope. This is what we call a Closure.</p>
<p><strong>Closure = Function + Remembered Values</strong></p>
<p>This is why closures are so important in job interviews. They show how deeply a programmer understands JavaScript. A programmer who understands closures can clearly grasp JavaScript's internal behavior, memory handling, and asynchronous flow.</p>
<h3 id="heading-the-importance-of-closures">The Importance of Closures</h3>
<p>JavaScript was originally created just for small interactive tasks in the browser, but now you can build large-scale applications, even backend systems, with it. The reason behind this is powerful concepts in JavaScript like Closures, Prototypes, and more.</p>
<p>Many people say, "I know var, let, const, so tell me about closures." But as you've seen, var, let, and const aren't that simple either. This is where the understanding of closures begins.</p>
<h2 id="heading-final-words">Final Words</h2>
<p>We covered a lot in this handbook! If reading this all at once feels overwhelming, you can break it into parts and read it step by step. I’ve tried to explain the whole topic very simply, piece by piece. If there are any areas that could be clearer, I appreciate your feedback. But once you’ve really understood and digested this info, you shouldn’t be intimidated by the word "Closure" ever again.</p>
<p>You can find all the source code from this tutorial in this <a target="_blank" href="https://github.com/logicbaselabs/understanding-closure/">GitHub repository</a>. If it helped you in any way, consider giving it a star to show your support!</p>
<p>If you found the information here valuable, feel free to share it with others who might benefit from it. I’d really appreciate your thoughts – mention me on X <a target="_blank" href="https://x.com/sumit_analyzen">@sumit_analyzen</a> or on Facebook <a target="_blank" href="https://www.facebook.com/sumit.analyzen">@sumit.analyzen</a>, <a target="_blank" href="https://www.youtube.com/@logicBaseLabs">watch</a> my coding tutorials, or simply <a target="_blank" href="https://www.linkedin.com/in/sumitanalyzen/">connect with me</a> on LinkedIn. You can also checkout my official website <a target="_blank" href="https://www.sumitsaha.me">sumitsaha.me</a> for more details about me.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Closures in Go ]]>
                </title>
                <description>
                    <![CDATA[ If you've written code in JavaScript, Python, or Rust, you've probably heard the word closure before. The concept has subtle differences in each language, but the core idea is the same: a closure is a function that captures variables from its surroun... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-closures-in-go/</link>
                <guid isPermaLink="false">68ffd791ca908949cd4f2afc</guid>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gabor Koos ]]>
                </dc:creator>
                <pubDate>Mon, 27 Oct 2025 20:35:29 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761597115311/04035f6b-6bd0-4889-8433-3f0d652f2586.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've written code in JavaScript, Python, or Rust, you've probably heard the word <em>closure</em> before. The concept has subtle differences in each language, but the core idea is the same: a closure is a function that captures variables from its surrounding scope. This allows the function to "remember" the environment in which it was created, even when it's executed outside that environment, which has powerful implications for how we write and structure our code.</p>
<p>In this article, we'll explore how closures work in Go, a statically typed language known for its simplicity and efficiency. We'll look at how to create closures, how they capture variables, and some practical use cases.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-closures-really-are-in-go">What Closures Really Are in Go</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-go-makes-this-work">How Go Makes This Work</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-multiple-independent-closures">Multiple Independent Closures</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-the-classic-loop-trap">The Classic Loop Trap</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-closures-in-go">How to Create Closures in Go</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-returning-closures-from-functions">Returning Closures From Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-named-inner-functions">Named Inner Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-inline-closures-in-loops-or-goroutines">Inline Closures in Loops or Goroutines</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-closures-with-parameters">Closures With Parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-capturing-multiple-variables">Capturing Multiple Variables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-closures-in-structs">Closures in Structs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-note-on-method-receivers">Note on Method Receivers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-takeaways">Key Takeaways</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-closures-and-concurrency">Closures and Concurrency</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-independent-state-across-goroutines">Independent State Across Goroutines</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-capturing-shared-variables-safely">Capturing Shared Variables Safely</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-patterns-with-closures">Practical Patterns with Closures</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-memoization-caching">Memoization / Caching</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-event-handlers-callbacks">Event Handlers / Callbacks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-encapsulated-pipelines-producers">Encapsulated Pipelines / Producers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-deferred-execution-with-captured-state">Deferred Execution with Captured State</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-interfaces-dynamically">How to Implement Interfaces Dynamically</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-takeaways-1">Key Takeaways</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-closures-affect-memory-and-performance">How Closures Affect Memory and Performance</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-variables-may-live-longer-than-expected">Variables May Live Longer Than Expected</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-many-closures-can-add-overhead">Many Closures Can Add Overhead</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-test-and-debug-closures">How to Test and Debug Closures</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-isolate-the-closure">Isolate the Closure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-check-captured-variables">Check Captured Variables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-logging-or-debug-prints">Use Logging or Debug Prints</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-test-concurrency-carefully">Test Concurrency Carefully</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-takeaways-2">Key Takeaways</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-and-takeaways-for-using-closures-in-go">Best Practices and Takeaways for Using Closures in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this article, you should have a basic understanding of Go programming, including functions and variable scope. If you're new to Go, consider checking out the <a target="_blank" href="https://tour.golang.org/">official Go tour</a> to get up to speed.</p>
<h2 id="heading-what-closures-really-are-in-go">What Closures Really Are in Go</h2>
<p>At its simplest, a closure in Go is a function that <strong>references variables defined outside of it</strong>. That may sound abstract, so let's start with an example you can run right away:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">counter</span><span class="hljs-params">()</span> <span class="hljs-title">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    n := <span class="hljs-number">0</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
        n++
        <span class="hljs-keyword">return</span> n
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    next := counter()
    fmt.Println(next()) <span class="hljs-comment">// 1</span>
    fmt.Println(next()) <span class="hljs-comment">// 2</span>
    fmt.Println(next()) <span class="hljs-comment">// 3</span>
}
</code></pre>
<p>When you call <code>counter()</code>, it returns another function, but that function <strong>keeps access to the variable</strong> <code>n</code> that lived inside counter.</p>
<p>Even though <code>counter()</code> has already finished running, <code>n</code> hasn't disappeared. Each time you call <code>next()</code>, it updates the same <code>n</code> that was created during the original <code>counter()</code> call.</p>
<p>This is the defining property of a closure:</p>
<blockquote>
<p>A closure "closes over" its environment, keeping the variables it needs alive for as long as the closure itself exists.</p>
</blockquote>
<h3 id="heading-how-go-makes-this-work">How Go Makes This Work</h3>
<p>Normally, local variables in Go live on the <strong>stack</strong>, which is cleared when a function returns.</p>
<p>But if a nested function needs to keep using one of those variables, Go's compiler performs what's called <em>escape analysis</em>: it sees that the variable will outlive the function call, so it moves that variable to the <strong>heap</strong>, where it can stay alive as long as something references it - in this case, the closure.</p>
<p>You can actually ask the compiler to show you this process:</p>
<pre><code class="lang-bash">go build -gcflags=<span class="hljs-string">"-m"</span> main.go
</code></pre>
<p>You might see output like:</p>
<pre><code class="lang-bash">./main.go:6:6: moved to heap: n
</code></pre>
<p>That tells you the variable <code>n</code> "escaped" the stack so the closure could use it safely later.</p>
<h3 id="heading-multiple-independent-closures">Multiple Independent Closures</h3>
<p>Each call to a function that returns a closure creates a new, independent environment:</p>
<pre><code class="lang-go">a := counter()
b := counter()
fmt.Println(a()) <span class="hljs-comment">// 1</span>
fmt.Println(a()) <span class="hljs-comment">// 2</span>
fmt.Println(b()) <span class="hljs-comment">// 1</span>
</code></pre>
<p>Here, <code>a</code> and <code>b</code> are two separate closures, each with its own <code>n</code>. Calling <code>a()</code> increments its own <code>n</code>, while calling <code>b()</code> starts from its own separate <code>n</code>.</p>
<h2 id="heading-the-classic-loop-trap">The Classic Loop Trap</h2>
<p>One of the most common surprises for Go developers comes when closures are used inside a loop. Even experienced programmers often fall into this trap.</p>
<p>Consider this example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    funcs := <span class="hljs-built_in">make</span>([]<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span>, 0)</span>
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
        funcs = <span class="hljs-built_in">append</span>(funcs, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
            fmt.Println(i)
        })
    }
    <span class="hljs-keyword">for</span> _, f := <span class="hljs-keyword">range</span> funcs {
        f()
    }
}
</code></pre>
<p>You might expect this to print <code>0</code>, <code>1</code>, and <code>2</code>, but it actually prints</p>
<pre><code class="lang-bash">3
3
3
</code></pre>
<p><strong>Why Does this Happen?</strong></p>
<p>Inside the loop, each function literal <strong>captures the variable</strong> <code>i</code> itself, not its value at that moment.</p>
<p>The loop reuses the same <code>i</code> variable for all iterations. By the time the loop finishes, <code>i</code> equals 3, and <strong>all the closures see this same</strong> <code>i</code> when they run later.</p>
<p><strong>How to Fix It</strong></p>
<p>There are two common idiomatic fixes:</p>
<ol>
<li>Shadow the loop variable:</li>
</ol>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
    i := i <span class="hljs-comment">// new variable shadows the loop variable</span>
    funcs = <span class="hljs-built_in">append</span>(funcs, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
        fmt.Println(i)
    })
}
</code></pre>
<ol start="2">
<li>Pass the variable as a parameter to an inner function:</li>
</ol>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
    funcs = <span class="hljs-built_in">append</span>(funcs, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">func</span><span class="hljs-params">()</span></span> {
        <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> { fmt.Println(x) }
    }(i))
}
</code></pre>
<p>Both approaches create a new variable for each iteration, so each closure captures its own independent value.</p>
<h2 id="heading-how-to-create-closures-in-go">How to Create Closures in Go</h2>
<p>There are a few different ways to create closures in Go. Let's explore some common patterns.</p>
<h3 id="heading-returning-closures-from-functions">Returning Closures From Functions</h3>
<p>The most common pattern is having a function return a closure that keeps its own state:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeCounter</span><span class="hljs-params">()</span> <span class="hljs-title">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    n := <span class="hljs-number">0</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
        n++
        <span class="hljs-keyword">return</span> n
    }
}

c1 := makeCounter()
fmt.Println(c1()) <span class="hljs-comment">// 1</span>
fmt.Println(c1()) <span class="hljs-comment">// 2</span>
</code></pre>
<p>Each call to <code>makeCounter</code> creates a new closure with its own <code>n</code>, as we saw earlier.</p>
<h3 id="heading-named-inner-functions">Named Inner Functions</h3>
<p>You can also give a name to a function literal for readability or debugging:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeCounter</span><span class="hljs-params">()</span> <span class="hljs-title">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    n := <span class="hljs-number">0</span>
    next := <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">incr</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
        n++
        <span class="hljs-keyword">return</span> n
    }
    <span class="hljs-keyword">return</span> next
}
</code></pre>
<p>This works the same way but gives the inner function a name (<code>incr</code>), which can be helpful in stack traces. Other than that, it behaves just like an anonymous function.</p>
<h3 id="heading-inline-closures-in-loops-or-goroutines">Inline Closures in Loops or Goroutines</h3>
<p>Closures are often defined inline, especially for loops or goroutines:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span></span> {
        fmt.Println(x)
    }(i)
}
</code></pre>
<p>Here, we pass <code>i</code> as a parameter to the closure, ensuring each goroutine gets its own copy of the value, avoiding the loop variable trap.</p>
<h3 id="heading-closures-with-parameters">Closures With Parameters</h3>
<p>Closures can accept their own arguments:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">adder</span><span class="hljs-params">(base <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">func</span><span class="hljs-params">(<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
        <span class="hljs-keyword">return</span> base + x
    }
}

add5 := adder(<span class="hljs-number">5</span>)
fmt.Println(add5(<span class="hljs-number">10</span>)) <span class="hljs-comment">// 15</span>
</code></pre>
<p>Here, <code>adder</code> returns a closure that adds a fixed <code>base</code> value to whatever argument it receives.</p>
<h3 id="heading-capturing-multiple-variables">Capturing Multiple Variables</h3>
<p>Closures can capture multiple outer variables:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">multiplier</span><span class="hljs-params">(factor <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">func</span><span class="hljs-params">(<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    offset := <span class="hljs-number">2</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
        <span class="hljs-keyword">return</span> x*factor + offset
    }
}

m := multiplier(<span class="hljs-number">3</span>)
fmt.Println(m(<span class="hljs-number">4</span>)) <span class="hljs-comment">// 14</span>
</code></pre>
<p>In this example, the closure captures both <code>factor</code> and <code>offset</code> from its surrounding scope - <code>factor</code> is a parameter, while <code>offset</code> is a local variable.</p>
<h3 id="heading-closures-in-structs">Closures in Structs</h3>
<p>Closures can also be stored in structs, just like any other function value. This is a useful pattern when you want objects with dynamic or stateful behavior.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Counter <span class="hljs-keyword">struct</span> {
    Next <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewCounter</span><span class="hljs-params">()</span> <span class="hljs-title">Counter</span></span> {
    n := <span class="hljs-number">0</span>
    <span class="hljs-keyword">return</span> Counter{
        Next: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
            n++
            <span class="hljs-keyword">return</span> n
        },
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    c := NewCounter()
    fmt.Println(c.Next()) <span class="hljs-comment">// 1</span>
    fmt.Println(c.Next()) <span class="hljs-comment">// 2</span>
}
</code></pre>
<p>Here, the <code>Next</code> field holds a closure that captures the variable <code>n</code>. Each instance of <code>Counter</code> has its own independent state, without needing a separate type or mutex.</p>
<p>This pattern shows how closures can act as lightweight objects: bundling behavior and state together.</p>
<h3 id="heading-note-on-method-receivers">Note on Method Receivers</h3>
<p>Closures in Go don't implicitly capture the method receiver like some languages do. If you want a closure to use the receiver inside a method, you typically assign it to a local variable:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Counter <span class="hljs-keyword">struct</span> {
    n <span class="hljs-keyword">int</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c *Counter)</span> <span class="hljs-title">MakeIncrementer</span><span class="hljs-params">()</span> <span class="hljs-title">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    r := c <span class="hljs-comment">// capture receiver explicitly</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
        r.n++
        <span class="hljs-keyword">return</span> r.n
    }
}
</code></pre>
<p>This ensures the closure references the intended receiver rather than introducing unexpected behavior.</p>
<p>Unlike JavaScript or Python, Go closures capture lexical variables, not the implicit <code>this</code> or <code>self</code>.</p>
<h3 id="heading-key-takeaways">Key Takeaways</h3>
<ul>
<li><p>Closures can be returned from functions, named, inlined, or even stored in structs.</p>
</li>
<li><p>They capture outer variables, not copies of their values.</p>
</li>
<li><p>Used this way, closures can replace small types or interfaces for lightweight encapsulation.</p>
</li>
</ul>
<h2 id="heading-closures-and-concurrency">Closures and Concurrency</h2>
<p>Closures are powerful in Go, but when you combine them with concurrency, their captured variables can act in unexpected ways if you're not careful.</p>
<h3 id="heading-independent-state-across-goroutines">Independent State Across Goroutines</h3>
<p>Each closure keeps its own captured variables alive, even when used in concurrent goroutines:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">makeWorker</span><span class="hljs-params">(start <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    counter := start
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
        counter++
        <span class="hljs-keyword">return</span> counter
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    worker1 := makeWorker(<span class="hljs-number">0</span>)
    worker2 := makeWorker(<span class="hljs-number">100</span>)

    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> { fmt.Println(worker1()) }() <span class="hljs-comment">// prints 1</span>
    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> { fmt.Println(worker2()) }() <span class="hljs-comment">// prints 101</span>
}
</code></pre>
<p>Here, <code>worker1</code> and <code>worker2</code> have independent <code>counter</code> variables, so they don't interfere with each other. Each closure maintains independent state, even in separate goroutines.</p>
<h3 id="heading-capturing-shared-variables-safely">Capturing Shared Variables Safely</h3>
<p>When multiple closures share a variable, you must coordinate access. For example:</p>
<pre><code class="lang-go">counter := <span class="hljs-number">0</span>
ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)

<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
        <span class="hljs-comment">// increments a shared variable</span>
        ch &lt;- <span class="hljs-number">1</span>
    }()
}

<span class="hljs-comment">// aggregate safely</span>
<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
    counter += &lt;-ch
}
fmt.Println(counter) <span class="hljs-comment">// 3</span>
</code></pre>
<p>The closure captures the outer variable <code>ch</code> (a channel), which is safe because channels serialize access. Using a buffered channel here wouldn't change the behavior of the closure: it still captures its own <code>n</code> and sends the values to the channel independently.</p>
<p>Closures themselves <strong>don't synchronize shared state, you still need channels or mutexes</strong>.</p>
<h2 id="heading-practical-patterns-with-closures">Practical Patterns with Closures</h2>
<p>Closures in Go aren't just a language curiosity, they're a powerful tool for writing stateful, reusable, and flexible code. Here are a few practical patterns that go beyond the basics.</p>
<h3 id="heading-memoization-caching">Memoization / Caching</h3>
<p>Closures can capture an internal map or cache to store results of expensive computations:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">memoize</span><span class="hljs-params">(f <span class="hljs-keyword">func</span>(<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span>) <span class="hljs-title">func</span><span class="hljs-params">(<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    cache := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">int</span>]<span class="hljs-keyword">int</span>{}
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
        <span class="hljs-keyword">if</span> val, ok := cache[x]; ok {
            <span class="hljs-keyword">return</span> val
        }
        result := f(x)
        cache[x] = result
        <span class="hljs-keyword">return</span> result
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fib := memoize(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(n <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
        <span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">1</span> {
            <span class="hljs-keyword">return</span> n
        }
        <span class="hljs-keyword">return</span> fib(n<span class="hljs-number">-1</span>) + fib(n<span class="hljs-number">-2</span>)
    })
    fmt.Println(fib(<span class="hljs-number">10</span>)) <span class="hljs-comment">// 55</span>
}
</code></pre>
<p>Here, the <code>memoize</code> function returns a closure that caches results of the Fibonacci function, avoiding redundant calculations.</p>
<h3 id="heading-event-handlers-callbacks">Event Handlers / Callbacks</h3>
<p>Closures are perfect for defining event handlers or callbacks that need to maintain state:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Button <span class="hljs-keyword">struct</span> {
    onClick <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(b *Button)</span> <span class="hljs-title">Click</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">if</span> b.onClick != <span class="hljs-literal">nil</span> {
        b.onClick()
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    count := <span class="hljs-number">0</span>
    button := Button{
        onClick: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
            count++
            fmt.Println(<span class="hljs-string">"Button clicked"</span>, count, <span class="hljs-string">"times"</span>)
        },
    }

    button.Click() <span class="hljs-comment">// Button clicked 1 times</span>
    button.Click() <span class="hljs-comment">// Button clicked 2 times</span>
}
</code></pre>
<p>In this example, the closure captures the <code>count</code> variable, allowing the button to keep track of how many times it has been clicked.</p>
<h3 id="heading-encapsulated-pipelines-producers">Encapsulated Pipelines / Producers</h3>
<p>Closures can wrap stateful logic for channels and pipelines:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">producer</span><span class="hljs-params">(start <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">func</span><span class="hljs-params">(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)</span></span> {
    n := start
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(ch <span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)</span></span> {
        <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
            ch &lt;- n
            n++
        }
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>, <span class="hljs-number">3</span>)
    <span class="hljs-keyword">go</span> producer(<span class="hljs-number">5</span>)(ch)
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
        fmt.Println(&lt;-ch) <span class="hljs-comment">// 5, 6, 7</span>
    }
}
</code></pre>
<p>Here, the <code>producer</code> function returns a closure that sends a sequence of numbers to a channel, maintaining its own state with <code>n</code>.</p>
<h3 id="heading-deferred-execution-with-captured-state">Deferred Execution with Captured State</h3>
<p>Using a closure with <code>defer</code> lets you capture variables at the moment the defer statement is executed, which is especially useful in loops or resource cleanup:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
        <span class="hljs-keyword">defer</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span></span> {
            fmt.Println(x)
        }(i) <span class="hljs-comment">// capture current i</span>
    }
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">2
1
0
</code></pre>
<p>Here, each deferred closure captures the value of <code>i</code> at the time of the <code>defer</code> statement, so they print in reverse order when the function exits.</p>
<h3 id="heading-how-to-implement-interfaces-dynamically">How to Implement Interfaces Dynamically</h3>
<p>Closures can also be used to implement interfaces without defining a full struct type. For example, a simple function can satisfy a single-method interface:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Greeter <span class="hljs-keyword">interface</span> {
    Greet() <span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">MakeGreeter</span><span class="hljs-params">(name <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">Greeter</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">struct</span>{ Greeter }{
        Greeter: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> { <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, "</span> + name },
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    g := MakeGreeter(<span class="hljs-string">"Alice"</span>)
    fmt.Println(g.Greet()) <span class="hljs-comment">// Hello, Alice</span>
}
</code></pre>
<p>Here, the closure captures <code>name</code>, allowing the returned object to implement the <code>Greet</code> method dynamically.</p>
<h3 id="heading-key-takeaways-1">Key Takeaways</h3>
<ul>
<li><p>Closures allow memoization and caching without extra structs.</p>
</li>
<li><p>Storing closures in structs provides customizable behavior for objects.</p>
</li>
<li><p>Closures can encapsulate stateful concurrent pipelines, keeping logic localized and safe.</p>
</li>
<li><p>Closures with <code>defer</code> capture variables at the time of deferment, useful for cleanup or logging.</p>
</li>
<li><p>They enable dynamic interface implementations without boilerplate types.</p>
</li>
</ul>
<h2 id="heading-how-closures-affect-memory-and-performance">How Closures Affect Memory and Performance</h2>
<p>Closures are powerful, but capturing variables from outer scopes has memory and performance implications.</p>
<h3 id="heading-variables-may-live-longer-than-expected">Variables May Live Longer Than Expected</h3>
<p>Because closures keep references to captured variables (and move them to the heap if necessary, as we saw earlier), these variables live as long as the closure itself, which can increase memory usage:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    bigData := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">byte</span>, <span class="hljs-number">10</span>_000_000) <span class="hljs-comment">// 10MB</span>
    f := <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> { <span class="hljs-keyword">return</span> <span class="hljs-built_in">len</span>(bigData) }
    _ = f
}
</code></pre>
<p>In this example, <code>bigData</code> remains in memory as long as the closure <code>f</code> exists, even if <code>bigData</code> is no longer needed elsewhere.</p>
<h3 id="heading-many-closures-can-add-overhead">Many Closures Can Add Overhead</h3>
<p>Each closure carries a small environment for its captured variables. Creating thousands of closures is usually fine, but in high-performance or memory-sensitive code, this can add measurable overhead.</p>
<ul>
<li><p>Captured variables may be heap-allocated.</p>
</li>
<li><p>Each closure has a small hidden struct for its environment.</p>
</li>
</ul>
<p>Alternatives include <strong>structs</strong> or <strong>plain functions</strong> when you need maximum efficiency.</p>
<h2 id="heading-how-to-test-and-debug-closures">How to Test and Debug Closures</h2>
<p>Closures can sometimes behave in unexpected ways when capturing variables or working with concurrency. Here are some tips to test and debug them effectively.</p>
<h3 id="heading-isolate-the-closure">Isolate the Closure</h3>
<p>Test the closure independently of its outer function to verify its behavior:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestCounter</span><span class="hljs-params">(t *testing.T)</span></span> {
    counter := makeCounter()
    <span class="hljs-keyword">if</span> counter() != <span class="hljs-number">1</span> {
        t.Error(<span class="hljs-string">"expected 1"</span>)
    }
    <span class="hljs-keyword">if</span> counter() != <span class="hljs-number">2</span> {
        t.Error(<span class="hljs-string">"expected 2"</span>)
    }
}
</code></pre>
<p>This ensures the closure maintains state correctly.</p>
<h3 id="heading-check-captured-variables">Check Captured Variables</h3>
<p>Remember: closures capture variables by reference, not value. Be mindful of loop variables or shared state:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++ {
    i := i <span class="hljs-comment">// shadow loop variable</span>
    t.Run(fmt.Sprintf(<span class="hljs-string">"i=%d"</span>, i), <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(t *testing.T)</span></span> {
        <span class="hljs-keyword">if</span> i != i { <span class="hljs-comment">// simplified check</span>
            t.Fail()
        }
    })
}
</code></pre>
<p>This helps avoid the loop trap in tests.</p>
<h3 id="heading-use-logging-or-debug-prints">Use Logging or Debug Prints</h3>
<p>Printing internal closure state is often the fastest way to debug subtle behavior:</p>
<pre><code class="lang-go">adder := <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(base <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">func</span><span class="hljs-params">(<span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(x <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
        fmt.Printf(<span class="hljs-string">"base=%d, x=%d\n"</span>, base, x)
        <span class="hljs-keyword">return</span> base + x
    }
}
result := adder(<span class="hljs-number">5</span>)(<span class="hljs-number">10</span>) <span class="hljs-comment">// logs: base=5, x=10</span>
</code></pre>
<h3 id="heading-test-concurrency-carefully">Test Concurrency Carefully</h3>
<p>When closures are used in goroutines, race conditions can creep in. Use the Go race detector:</p>
<pre><code class="lang-bash">go <span class="hljs-built_in">test</span> -race ./...
</code></pre>
<p>This flags any shared variable access that isn’t properly synchronized.</p>
<h3 id="heading-key-takeaways-2">Key Takeaways</h3>
<ul>
<li><p>Test closures independently to ensure captured state behaves as expected.</p>
</li>
<li><p>Be cautious with loop variables and shared state.</p>
</li>
<li><p>Use logging and the race detector to debug concurrency issues.</p>
</li>
</ul>
<h2 id="heading-best-practices-and-takeaways-for-using-closures-in-go">Best Practices and Takeaways for Using Closures in Go</h2>
<p>Closures are a versatile feature in Go, but like any tool, they work best when used thoughtfully. Here are some practical guidelines:</p>
<ul>
<li><p><strong>Encapsulate state cleanly</strong>: Use closures to maintain private state without introducing extra structs or types. Counters, memoization caches, and small factories are common patterns.</p>
</li>
<li><p><strong>Be careful in loops</strong>: Always capture loop variables correctly to avoid the classic loop trap. Shadowing the variable or passing it as a parameter to the closure are idiomatic solutions.</p>
</li>
<li><p><strong>Handle concurrency explicitly</strong>: Closures can safely maintain independent state in goroutines, but they do not synchronize shared state automatically. When multiple closures share variables, coordinate access with channels or mutexes.</p>
</li>
<li><p><strong>Mind memory usage</strong>: Captured variables may escape to the heap, so long-lived closures can retain more memory than expected. Avoid capturing large objects unless necessary.</p>
</li>
<li><p><strong>Leverage closures in structs</strong>: Storing closures in struct fields allows objects to have dynamic or customizable behavior without extra boilerplate, making your code more flexible.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Closures in Go allow functions to carry state, encapsulate behavior, and interact safely with concurrency patterns, all while keeping your code clean and expressive. By understanding how closures capture variables, how they behave in loops and goroutines, and their memory implications, you can use them confidently to write more idiomatic and maintainable Go code.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Do Closures Work in JavaScript? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Sally and Joe are two love birds. They shared everything with each other and soon enough it was almost impossible to think that anything could come between them. One day, they had a quarrel which built up to a break up.    It was hard for Joe and ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understand-javascript-closures/</link>
                <guid isPermaLink="false">66c37506d0cda7b58da26c34</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Austin Asoluka ]]>
                </dc:creator>
                <pubDate>Tue, 07 May 2024 07:13:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/hand-1222229_1280-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sally and Joe are two love birds. They shared everything with each other and soon enough it was almost impossible to think that anything could come between them. One day, they had a quarrel which built up to a break up.   </p>
<p>It was hard for Joe and he wanted "closure". Although Sally already moved on, Joe found closure by taking time to think through the whole experience, recalling "shared memories" and properly introspecting. Even though the relationship had ended, Joe still had something that reminded him of Sally and he was cool with that.</p>
<p>The story ends.</p>
<p>If this is your first time hearing of the term "closure", I'll do you the honor of telling you what it means.  </p>
<p>Closure is simply the act of bringing something to an end. Closure in a relationship refers to the sense of peace and understanding you get after the relationship comes to an end. It's that feeling of "letting go" and being able to move on.  </p>
<p>For some people, getting closure involves holding on to a "shared memory" with the other party, or something (perhaps an item) that reminds them of the other.</p>
<p>Now that you are familiar with the term closure as it relates to humans, let's try to understand it in terms of the relationship between functions in JavaScript.</p>
<p>In JavaScript, a closure is said to be created when a function retains access to resource(s) declared in it's parent scope even after the parent function has been removed from the call stack.</p>
<p><strong>Note</strong>: In JavaScript, when a function is said have been popped-off/removed from the stack, it means that the function has completed its life-span (is done executing), and all of its resources have been removed from memory and are no longer accessible.</p>
<p>Think of the call stack like the world, while parent and child are two entities in the world.</p>
<p>In this case, <code>parent</code> is the function that has completed execution and logically, everything about it should be out of reach. But because of the concept of closure, even when the relationship between the <code>parent</code> and <code>child</code> functions has ended – that is, when the parent gets popped-off the stack (removed from the world) – the child function still remembers everything they shared together.</p>
<p><strong>Note</strong>: Everything they shared together as used above simply means the variables declared in the <code>parent</code> function which are used by the <code>child</code> function.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">parent</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> a = <span class="hljs-string">"Az"</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">child</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(a);
    }
}
</code></pre>
<p>In the code snippet above, the variable <code>a</code> is what the <code>parent</code> and <code>child</code> functions shares together.  </p>
<p>So even when <code>parent</code> gets removed from the call stack, <code>child</code> still remembers the value of <code>a</code> for as long as it lives.</p>
<p>If you stop reading at this point, you already know what closure is conceptually. But if you want to fully understand it and never forget, we'll have to take a deep dive into the workings of JavaScript.</p>
<h2 id="heading-deep-dive-into-the-concept-of-closure">Deep Dive into the Concept of Closure.</h2>
<p>To really understand closures in JavaScript, you have to be familiar with the following concepts:</p>
<ol>
<li><p>The concept of functions being first-class citizens in JavaScript. This means that:</p>
</li>
<li><p>Functions can be assigned to variables as values</p>
</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getName = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Allice'</span>   
};
</code></pre>
<p>Now you can simply call the function <code>getName</code> just like you would call any other function using the parenthesis like this <code>getName()</code>  </p>
<p>Think of functions as callable objects. This means, just like we can assign objects to variables and pass them around, you can do same with functions. The difference between them is that you can call a function when you need the code in it to execute.</p>
<ul>
<li>Functions can be passed into other functions as arguments</li>
</ul>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(getName, <span class="hljs-number">5000</span>)
</code></pre>
<p>As you can see in the code snippet above, during the invocation of the <code>setTimeout</code> function, we passed the <code>getName</code> function into it as an argument. Again, this is because functions are simply objects that are callable.   </p>
<p>Take note that when we pass the <code>getName</code> function into the <code>setTimeout</code> function, we are not calling/invoking it. We are simply passing the function as a value.   </p>
<p>If we called the function, we'd be passing its return value instead and that's a significant difference there.  </p>
<p>I'd also like to bring to your notice that mentioning the name of a function is simply referencing that function. Behind the scene, the function name gets replaced by the function itself.  </p>
<p>That is, this code <code>setTimeout(getName, 5000)</code> is equivalent to the code below;</p>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Allice'</span>   
}, <span class="hljs-number">5000</span>)
</code></pre>
<p>The function name gets replaced with the function itself during execution just like a regular variable name gets replaced by its value during execution.</p>
<ul>
<li>Functions can be returned from other functions.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyBy</span> (<span class="hljs-params">numberToMultiplyBy</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">numberToMultiply</span>) </span>{
        <span class="hljs-keyword">return</span> numberToMultiply * numberToMultiplyBy
    }
}
</code></pre>
<p>Taking a close look at the code snippet above, you'll notice that we have a function called <code>multiplyBy</code> which expects an argument during invocation and returns a new function.   </p>
<p>The interesting thing to notice here is that when we call the returned function, it expects an argument too, but this time, it remembers the argument passed into the original <code>multiplyBy</code> function ( <code>numberToMultiplyBy</code> ), then multiplies the value passed into itself ( <code>numberToMultiply</code> ) with the value passed into its parent function, and returns the result.  </p>
<p>Carefully observe the code below which makes use of the higher-order function <code>multiplyBy</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> multiplyByTwo = multiplyBy(<span class="hljs-number">2</span>)
<span class="hljs-keyword">const</span> result = multiplyByTwo(<span class="hljs-number">8</span>)

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// 16</span>
</code></pre>
<ol start="2">
<li>The concept of Higher-order functions: This is the second concept you need to be aware of to understand closure.</li>
</ol>
<p>A higher order function is a function which:</p>
<ul>
<li>Accepts a function as an argument. For example: <code>setTimeout</code>, <code>Promise</code>, and so on.</li>
<li>Returns a function. For example: <code>multiplyBy</code> function declared above.</li>
<li>Or fulfils the first and second items above.</li>
</ul>
<p>Now that you understand that functions are first-class citizens and you've seen implementations of a higher-order function, we can proceed to talk about closures.</p>
<p>Recall that a closure occurs when a child function holds reference to/remembers a value or resource which belonged to its parent function even after the parent function has been removed from the call stack.</p>
<p>Consider this code:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sally</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> age = <span class="hljs-number">64</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">joe</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">const</span> data = {
            <span class="hljs-attr">name</span>: <span class="hljs-string">"Joe"</span>,
            <span class="hljs-attr">parentName</span>: <span class="hljs-string">"Sally"</span>,
            <span class="hljs-attr">parentAge</span>: age
        }
        <span class="hljs-keyword">return</span> data
    }
}
</code></pre>
<p>In the code snippet above, we can observe that:</p>
<ul>
<li><code>sally</code> is the parent function and it declares a scope</li>
<li><code>age</code> is a variable declared within the <code>sally</code> scope</li>
<li><code>joe</code> is a function which lives in the <code>sally</code> scope and is returned by the <code>sally</code> function. You should also note that:  </li>
<li><code>joe</code> defines its own scope which is a child scope of the <code>sally</code> scope  </li>
<li>within the <code>joe</code> scope, we make reference to the variable <code>age</code> which belongs to <code>sally</code> scope (this is where closure happens because <code>joe</code> is referring or holding on to a resource/variable which belongs to <code>sally</code>).</li>
</ul>
<p>Because <code>joe</code> holds a reference to the variable <code>age</code> which belongs to <code>sally</code>, even when <code>sally</code> has been popped-off the call stack and its scope discarded, <code>joe</code> will retain access to the <code>age</code> variable because of the concept of closure.</p>
<p>So in the code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> joe = sally() <span class="hljs-comment">// sally is invoked and returns the joe function</span>
<span class="hljs-keyword">const</span> joeyData = joe() <span class="hljs-comment">// joe function is invoked and returns an object</span>

<span class="hljs-built_in">console</span>.log(joeyData) <span class="hljs-comment">// we log the object returned.</span>
</code></pre>
<p>You can observe that even though <code>sally</code> is called and popped-off the stack, when you invoke <code>joe</code> and log the return value of <code>joe</code> to the console, it still remembers the <code>age</code> of sally during the execution (which we can access in the returned object like so <code>joeyData.parentAge</code>).</p>
<h2 id="heading-summary">Summary</h2>
<p>When a child function refers to variables used in its parent scope, closure occurs.<br>Closure is like a memory box which stores all the items of the parent scope that are referred to from the child scope.</p>
<p>A look at the slides below should cement the knowledge you've gained so far and hopefully everything will fall in place.</p>
<div class="embed-wrapper"><iframe class="speakerdeck-iframe" src="https://speakerdeck.com/player/361482321f264b4aa170e04776365956" style="border:0px;background:padding-box padding-box rgba(0, 0, 0, 0.1);margin:0px;padding:0px;border-radius:6px;box-shadow:rgba(0, 0, 0, 0.2) 0px 5px 40px;width:100%;height:auto;aspect-ratio:560 / 432" title="Embedded content" loading="lazy"></iframe></div>

<p>Closures unlocked? Level up your JavaScript skills with more full-stack development tutorials on my <a target="_blank" href="https://www.youtube.com/@asoluka_tee">YouTube</a> channel. Subscribe now for my next playlist on fundamental JavaScript concepts!</p>
<p>Thanks for reading! Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Closure in JavaScript – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In this article, we are going to talk about closures in JavaScript. I'll walk you through the definition of a closure, a simple day-to-day fetch utility closure example, and some of the advantages and disadvantages of using closures.  Table of Conten... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-closures-explained-with-example/</link>
                <guid isPermaLink="false">66bb554d4c9d249e52882f2b</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Keyur Paralkar ]]>
                </dc:creator>
                <pubDate>Wed, 13 Apr 2022 18:57:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/safar-safarov-LKsHwgzyk7c-unsplash-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, we are going to talk about closures in JavaScript. I'll walk you through the definition of a closure, a simple day-to-day fetch utility closure example, and some of the advantages and disadvantages of using closures. </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a> </li>
<li><a class="post-section-overview" href="#heading-what-are-closures">What are closures</a>?</li>
<li><a class="post-section-overview" href="#heading-use-case-of-closure-creating-a-fetch-utility-with-closures">Use case of closures</a></li>
<li><a class="post-section-overview" href="#heading-advantages-of-closures">Advantages of closures</a></li>
<li><a class="post-section-overview" href="#heading-disadvantages-of-closures">Disadvantages of closures</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<p>Without further ado, let's get started.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>You should have a good understanding of the following topics to understand this article:</p>
<ul>
<li>How JavaScript's <a target="_blank" href="https://www.freecodecamp.org/news/javascript-execution-context-and-hoisting/">execution context</a> works</li>
<li>What the <a target="_blank" href="https://www.freecodecamp.org/news/javascript-fetch-api-tutorial-with-js-fetch-post-and-header-examples/">Fetch API</a> is and how to use it</li>
</ul>
<h2 id="heading-what-are-closures">What are closures?</h2>
<p>Closures are functions that have access to the variables that are present in their scope chain even if the outer function ceases to exist.</p>
<p>To understand this in more detail, let's understand what a scope chain is. Scope chain refers to the fact that parent scope does not have access to the variables inside its children's scope, but the children's scope does have access to the variables present in its parent scopes. </p>
<p>Let's make this clearer by taking a look at an example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> buttonProps = <span class="hljs-function">(<span class="hljs-params">borderRadius</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> createVariantButtonProps = <span class="hljs-function">(<span class="hljs-params">variant, color</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> newProps = {
            borderRadius,
            variant,
            color
        };
        <span class="hljs-keyword">return</span> newProps;
    }
    <span class="hljs-keyword">return</span> createVariantButtonProps;
}
</code></pre>
<p>As you can see, we have a function called <code>buttonProps</code>. This function accepts <code>borderRadius</code> as an argument. Let's consider the <code>buttonProps</code> function as our parent function.</p>
<p>We have another function that has been defined inside the parent function, that is <code>createVariantButtonProps</code>. This function will accept <code>variant</code> and <code>color</code> as an argument and return an object that constitutes a variable <code>borderRadius</code> that is present outside its scope.</p>
<p>But a question arises as to how the inner function resolves the variables that are present in the parent scope.</p>
<p>Well, this is possible via lexical scoping. Using lexical scoping, the JS parser knows how to resolve variables present in its current scope or in fact knows how to resolve variables present in the nested functions. </p>
<p>So based on the above explanation, <code>createVariantButtonProps</code> will have access to the variables present in its outer function <code>buttonProps</code>.</p>
<p>In the above example, the inner function <code>createVariantButtonProps</code> is a closure. To understand closures in detail we will first go through the characteristics of closures which are as follows:</p>
<ul>
<li>Even if the outer function ceases to exist, a closure still has access to its parent variables.</li>
<li>Closures do not have access to their outer function’s <code>args</code> parameter.</li>
</ul>
<p>Let's get into more detail on each of these points.</p>
<h3 id="heading-even-if-the-outer-function-ceases-to-exist-it-still-has-access-to-its-parent-variables">Even if the outer function ceases to exist, it still has access to its parent variables.</h3>
<p>This is the basic functionality of any closure. This is their main life motto aka their working principle.</p>
<p>To see this in action we will now execute the above <code>buttonProps</code> function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> primaryButton = buttonProps(<span class="hljs-string">"1rem"</span>);
</code></pre>
<p>Calling the <code>buttonProps</code> function will return us another function that is our closure.</p>
<p>Now let's execute this closure:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> primaryButtonProps = primaryButton(<span class="hljs-string">"primary"</span>, <span class="hljs-string">"red"</span>);
</code></pre>
<p>Once the closure is executed, it returns the following object:</p>
<pre><code class="lang-js">{
   <span class="hljs-string">"borderRadius"</span>:<span class="hljs-string">"1rem"</span>,
   <span class="hljs-string">"variant"</span>:<span class="hljs-string">"primary"</span>,
   <span class="hljs-string">"color"</span>:<span class="hljs-string">"red"</span>
}
</code></pre>
<p>Here again a question arises: How does the <code>primaryButton</code> function have access to the variable <code>borderRadius</code> that was not present inside it?</p>
<p>If we go through the definition of closures, and scope chaining that we discussed earlier, it perfectly fits into that instance.</p>
<p>Let's dig deeper into why closures still have access to the variables that are defined outside their scope, even if the outer function ceases to exists – for example, <code>borderRadius</code>?  </p>
<p>The answer is simple: closures do not store static values. Instead, they store references to the variables present inside the scope chain. In this way, even if the outer function dies, the inner function, that is a closure, still has access to its parent variables.</p>
<h2 id="heading-use-case-of-closure-creating-a-fetch-utility-with-closures">Use case of closure: Creating a fetch utility with closures</h2>
<p>Now that we've learned what closures are, we will create a nice general purpose utility function. It will handle different request methods such as GET and POST with REST APIs.</p>
<p>For this use case, </p>
<ul>
<li>We will be using <a target="_blank" href="https://jsonplaceholder.typicode.com/">JSON placeholder APIs</a>. This provides us with some fake data which we can edit using REST APIs.</li>
<li>We will be using JavaScript's <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/fetch">fetch</a> API.</li>
</ul>
<p>Let's first discuss why we even need to design such a utility. There are couple of reasons:</p>
<ul>
<li>For every fetch call, we don’t want to define the base URL (or other common parameters) all the time. So we will create a mechanism that will store the base URL/parameters as a state.</li>
<li>To remove redundant code.</li>
<li>To provide modularity in the codebase.</li>
</ul>
<p>Let's dive into the details of this utility. Our fetch utility will look like below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchUtility = <span class="hljs-function">(<span class="hljs-params">baseURL, headers</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> createFetchInstance = <span class="hljs-function">(<span class="hljs-params">route, requestMethod, data</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> tempReq = <span class="hljs-keyword">new</span> Request(<span class="hljs-string">`<span class="hljs-subst">${baseURL}</span><span class="hljs-subst">${route}</span>`</span>, {
      <span class="hljs-attr">method</span>: requestMethod,
      headers,
      <span class="hljs-attr">data</span>: data || <span class="hljs-literal">null</span>
    });
    <span class="hljs-keyword">return</span> [fetch, tempReq];
  };

  <span class="hljs-keyword">return</span> createFetchInstance;
};
</code></pre>
<ul>
<li><code>fetchUtility</code> accepts two parameters that are <code>baseURL</code> and <code>headers</code>. These will be used later in the closure to construct the base URL along with the headers.</li>
<li>Then we have <code>createFetchInstance</code>, which accepts <code>route</code> <code>requestMethod</code> and <code>data</code> as parameters. </li>
<li>Next, this function creates a new request object that will construct our URL using the code: <code>${baseURL}${route}</code>. We also pass in an object which consists of the request method type, headers, and data if available.</li>
<li>Then we return the instance of a fetch API along with the request object.</li>
<li>Lastly, we return the <code>createFetchInstance</code> function.</li>
</ul>
<p>Now let's see this function in action. Call our <code>fetchUtility</code> function to initialize the <code>baseURL</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchInstance = fetchUtility(<span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>);
</code></pre>
<ul>
<li>If we observe, the <code>fetchInstance</code> now has the value of the closure of the function <code>fetchUtility</code>.</li>
<li>Next, we pass the route and the type of the request to the closure <code>fetchInstance</code>:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [getFunc, getReq] = fetchInstance(<span class="hljs-string">"/todos/1"</span>, <span class="hljs-string">"GET"</span>);
</code></pre>
<p>As you can see this returns us an array of fetch API instance and the request body that we configured.</p>
<p>Finally, we can make use of the <code>getFunc</code> fetch API to call the request <code>getReq</code> like below:</p>
<pre><code class="lang-javascript">getFunc(getReq)
  .then(<span class="hljs-function">(<span class="hljs-params">resp</span>) =&gt;</span> resp.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data));
</code></pre>
<p>We can also create a POST request similar to the above GET request. We just need to call the <code>fetchInstance</code> again as below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [postFunc, postReq] = fetchInstance(
  <span class="hljs-string">"/posts"</span>,
  <span class="hljs-string">"POST"</span>,
  <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">title</span>: <span class="hljs-string">"foo"</span>,
    <span class="hljs-attr">body</span>: <span class="hljs-string">"bar"</span>,
    <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>
  })
);
</code></pre>
<p>And to execute this post request we can do the similar operation that we did for the GET request:</p>
<pre><code class="lang-javascript">postFunc(postReq)
  .then(<span class="hljs-function">(<span class="hljs-params">resp</span>) =&gt;</span> resp.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data));
</code></pre>
<p>If we closely look at the above example, we can see that the inner function <code>createFetchInstance</code> has access to the variables present in its scope chain. With the help of lexical scoping, during its definition of <code>createFetchInstance</code> it resolves the variable names. </p>
<p>In this way the closure references the variables <code>baseURL</code> and <code>headers</code> during its definition even after the outer function <code>fetchUtility</code> has ceased to exist.</p>
<p>If we think of closures from a different perspective, then closures help us to maintain a state like <code>baseURL</code> and <code>headers</code> that we can use across function calls.</p>
<h2 id="heading-advantages-of-closures">Advantages of closures</h2>
<p>Here are some advantages of closures:</p>
<ul>
<li>They allow you to attach variables to an execution context.</li>
<li>Variables in closures can help you maintain a state that you can use later.</li>
<li>They provide data encapsulation.</li>
<li>They help remove redundant code.</li>
<li>They help maintain modular code.</li>
</ul>
<h2 id="heading-disadvantages-of-closures">Disadvantages of closures</h2>
<p>There are two main disadvantages of overusing closures:</p>
<ul>
<li>The variables declared inside a closure are not garbage collected.</li>
<li>Too many closures can slow down your application. This is actually caused by duplication of code in the memory.</li>
</ul>
<h2 id="heading-summary">Summary</h2>
<p>So in this way closures can be really useful if you want to deal with or implement certain design patterns. They also help you write neat and modular code. </p>
<p>If you liked the idea of closures, then I would recommend reading further on the following topics:</p>
<ul>
<li><a target="_blank" href="https://www.patterns.dev/posts/classic-design-patterns/">Design patterns</a></li>
<li><a target="_blank" href="https://stackoverflow.com/questions/16032840/javascript-anonymous-closure">Anonymous closures</a></li>
</ul>
<p>Thank you for reading!</p>
<p>Follow me on <a target="_blank" href="https://twitter.com/keurplkar">Twitter</a>, <a target="_blank" href="https://github.com/keyurparalkar">GitHub</a>, and <a target="_blank" href="https://www.linkedin.com/in/keyur-paralkar-494415107/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Scope and Closures in JavaScript – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Zach Snoek You may have come across or written code similar to this when writing JavaScript: function sayWord(word) {     return () => console.log(word); } const sayHello = sayWord("hello"); sayHello(); // "hello" This code is interesting for a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/scope-and-closures-in-javascript/</link>
                <guid isPermaLink="false">66d461714bc8f441cb6df82d</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Scope ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 01 Feb 2022 23:52:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/karine-avetisyan-ipuiM-36tAg-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Zach Snoek</p>
<p>You may have come across or written code similar to this when writing JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayWord</span>(<span class="hljs-params">word</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(word);
}

<span class="hljs-keyword">const</span> sayHello = sayWord(<span class="hljs-string">"hello"</span>);

sayHello(); <span class="hljs-comment">// "hello"</span>
</code></pre>
<p>This code is interesting for a couple of reasons. First, we can access <code>word</code> in the function returned from <code>sayWord</code>. Second, we have access to <code>word</code>’s value when we call <code>sayHello</code> – even though we call <code>sayHello</code> where we do not otherwise have access to <code>word</code>.</p>
<p>In this article, we’ll learn about scope and closures, which enable this behavior.</p>
<h2 id="heading-introducing-scope-in-javascript">Introducing Scope in JavaScript</h2>
<p>Scope is the first piece that will help us understand the previous example. A variable’s scope is the part of a program where it is available for use. </p>
<p>JavaScript variables are lexically scoped, meaning that we can determine a variable’s scope from where it is declared in the source code. (This is not entirely true: <code>var</code> variables are not lexically scoped, but we will discuss that shortly.)</p>
<p>Take the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">const</span> foo = <span class="hljs-string">"foo"</span>;
    <span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// "foo"</span>
}
</code></pre>
<p>The <code>if</code> statement introduces a block scope by using a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block">block statement</a>. We say that <code>foo</code> is block-scoped to the <code>if</code> statement. This means it can only be accessed from within that block.</p>
<p>If we try to access <code>foo</code> outside of the block, we get a <code>ReferenceError</code> because it is out of scope:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">const</span> foo = <span class="hljs-string">"foo"</span>;
    <span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// "foo"</span>
}

<span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// Uncaught ReferenceError: foo is not defined</span>
</code></pre>
<p>Block statements in other forms, such as <code>for</code> and <code>while</code> loops, will also create a scope for block-scoped variables. For instance, <code>foo</code> is scoped within a function body below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayFoo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> foo = <span class="hljs-string">"foo"</span>;
    <span class="hljs-built_in">console</span>.log(foo);
}

sayFoo(); <span class="hljs-comment">// "foo"</span>

<span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// Uncaught ReferenceError: foo is not defined</span>
</code></pre>
<h2 id="heading-nested-scopes-and-functions">Nested Scopes and Functions</h2>
<p>JavaScript allows nested blocks and therefore nested scopes. Nested scopes create a scope tree or scope chain. </p>
<p>Consider the code below, which nests multiple block statements:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">const</span> foo = <span class="hljs-string">"foo"</span>;
    <span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// "foo"</span>

    <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-keyword">const</span> bar = <span class="hljs-string">"bar"</span>;
        <span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// "foo"</span>

        <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
            <span class="hljs-built_in">console</span>.log(foo, bar); <span class="hljs-comment">// "foo bar"</span>
        }
    }
}
</code></pre>
<p>JavaScript also allows us to nest functions:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params">bar</span>) </span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(bar);
    }

    baz();
}

foo(<span class="hljs-string">"bar"</span>); <span class="hljs-comment">// "bar"</span>
</code></pre>
<p>As expected, we can access variables from their direct scope (the scope where they get declared). We can also access variables from their inner scopes (the scopes that nest within their direct scope). That is, we can access variables from the scope they get declared in and from every inner scope.</p>
<p>Before we go further, we should clarify the difference in this behavior between variable declaration types.</p>
<h2 id="heading-scope-of-let-const-and-var-in-javascript">Scope of let, const, and var in JavaScript</h2>
<p>We can create variables with the <code>let</code>, <code>const</code>, and <code>var</code> declarations. For <code>let</code> and <code>const</code>, block scoping works as explained above. However, <code>var</code> behaves differently.</p>
<h3 id="heading-let-and-const">let and const</h3>
<p><code>let</code> and <code>const</code> create block-scoped variables. When declared within a block, they are only accessible within that block. This behavior was demonstrated in our previous examples:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">const</span> foo = <span class="hljs-string">"foo"</span>;
    <span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// "foo"</span>
}

<span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// Uncaught ReferenceError: foo is not defined</span>
</code></pre>
<h3 id="heading-var">var</h3>
<p>Variables created with <code>var</code> are scoped to their nearest function or the global scope (which we will discuss shortly). They are not block scoped:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-keyword">var</span> foo = <span class="hljs-string">"foo"</span>;
    }
    <span class="hljs-built_in">console</span>.log(foo);
}

foo(); <span class="hljs-comment">// "foo"</span>
</code></pre>
<p><code>var</code> can create confusing situations, and this information is only included for completeness. It is best to use <code>let</code> and <code>const</code> when possible. The rest of this article will pertain only to <code>let</code> and <code>const</code> variables.</p>
<p>If you’re interested in how <code>var</code> behaves in the example above, you should check out <a target="_blank" href="https://www.freecodecamp.org/news/what-is-hoisting-in-javascript/">my article on hoisting</a>.</p>
<h2 id="heading-global-and-module-scope-in-javascript">Global and Module Scope in JavaScript</h2>
<p>In addition to block scopes, variables can be scoped to the global and module scope.</p>
<p>In a web browser, the global scope is at the top level of a script. It is the root of the scope tree that we described earlier, and it contains all other scopes. Thus, creating a variable in the global scope makes it accessible in every scope:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> foo = <span class="hljs-string">"foo"</span>;
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// "foo"</span>

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
            <span class="hljs-built_in">console</span>.log(foo);
        }
    }

    bar(); <span class="hljs-comment">// "foo"</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Each module also has its own scope. Variables declared at the module level are only available within that module – they are not global:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> foo = <span class="hljs-string">"foo"</span>;
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-built_in">console</span>.log(foo); <span class="hljs-comment">// Uncaught ReferenceError: foo is not defined</span>
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<h2 id="heading-closures-in-javascript">Closures in JavaScript</h2>
<p>Now that we understand scope, let’s go back to the example that we saw in the introduction:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayWord</span>(<span class="hljs-params">word</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(word);
}

<span class="hljs-keyword">const</span> sayHello = sayWord(<span class="hljs-string">"hello"</span>);

sayHello(); <span class="hljs-comment">// "hello"</span>
</code></pre>
<p>Recall that there were two interesting points about this example:</p>
<ol>
<li>The returned function from <code>sayWord</code> can access the <code>word</code> parameter</li>
<li>The returned function maintains the value of <code>word</code> when <code>sayHello</code> is called outside the scope of <code>word</code></li>
</ol>
<p>The first point can be explained by lexical scope: the returned function can access <code>word</code> because it exists in its outer scope.</p>
<p>The second point is because of closures: A closure is a function combined with references to the variables defined outside of it. Closures maintain the variable references, which allow functions to access variables outside of their scope. They “enclose” the function and the variables in its environment.</p>
<h2 id="heading-examples-of-closures-in-javascript">Examples of Closures in JavaScript</h2>
<p>You have probably encountered and used closures frequently without being aware of it. Let’s explore some more ways to use closures.</p>
<h3 id="heading-callbacks">Callbacks</h3>
<p>It is common for a callback to reference a variable declared outside of itself. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getCarsByMake</span>(<span class="hljs-params">make</span>) </span>{
    <span class="hljs-keyword">return</span> cars.filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x.make === make);
}
</code></pre>
<p><code>make</code> is available in the callback because of lexical scoping, and the value of <code>make</code> is persisted when the anonymous function is called by <code>filter</code> because of a closure.</p>
<h3 id="heading-storing-state">Storing state</h3>
<p>We can use closures to return objects from functions that store state. Consider the following <code>makePerson</code> function which returns an object that can store and change a <code>name</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makePerson</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">let</span> _name = name;

    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">setName</span>: <span class="hljs-function">(<span class="hljs-params">newName</span>) =&gt;</span> (_name = newName),
        <span class="hljs-attr">getName</span>: <span class="hljs-function">() =&gt;</span> _name,
    };
}

<span class="hljs-keyword">const</span> me = makePerson(<span class="hljs-string">"Zach"</span>);
<span class="hljs-built_in">console</span>.log(me.getName()); <span class="hljs-comment">// "Zach"</span>

me.setName(<span class="hljs-string">"Zach Snoek"</span>);
<span class="hljs-built_in">console</span>.log(me.getName()); <span class="hljs-comment">// "Zach Snoek"</span>
</code></pre>
<p>This example illustrates how closures do not just freeze the values of variables from a function’s outer scope during creation. Instead, they maintain the references throughout the closure’s lifetime.</p>
<h3 id="heading-private-methods">Private methods</h3>
<p>If you’re familiar with object-oriented programming, you might have noticed that our previous example closely resembles a class that stores private state and exposes public getter and setter methods. We can extend this object-oriented parallel further by using closures to implement private methods:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">makePerson</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">let</span> _name = name;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">privateSetName</span>(<span class="hljs-params">newName</span>) </span>{
        _name = newName;
    }

    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">setName</span>: <span class="hljs-function">(<span class="hljs-params">newName</span>) =&gt;</span> privateSetName(newName),
        <span class="hljs-attr">getName</span>: <span class="hljs-function">() =&gt;</span> _name,
    };
}
</code></pre>
<p><code>privateSetName</code> is not directly accessible to consumers and it can access the private state variable <code>_name</code> through a closure.</p>
<h3 id="heading-react-event-handlers">React event handlers</h3>
<p>Lastly, closures are common in React event handlers. The following <code>Counter</code> component is modified from the <a target="_blank" href="https://reactjs.org/docs/hooks-reference.html#functional-updates">React docs</a>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params">{ initialCount }</span>) </span>{
    <span class="hljs-keyword">const</span> [count, setCount] = React.useState(initialCount);

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(initialCount)}&gt;Reset<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount((prevCount) =&gt; prevCount - 1)}&gt;
                -
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount((prevCount) =&gt; prevCount + 1)}&gt;
                +
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> alert(count)}&gt;Show count<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/&gt;</span></span>
    );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Counter</span> <span class="hljs-attr">initialCount</span>=<span class="hljs-string">{0}</span> /&gt;</span></span>;
}
</code></pre>
<p>Closures make it possible for:</p>
<ul>
<li>the reset, decrement, and increment button click handlers to access <code>setCount</code></li>
<li>the reset button to access <code>initialCount</code> from <code>Counter</code>'s props</li>
<li>and the “Show count” button to display the <code>count</code> state.</li>
</ul>
<p>Closures are important in other parts of React, such as props and hooks. Discussion about these topics is out of scope for this article. I recommend reading <a target="_blank" href="https://epicreact.dev/how-react-uses-closures-to-avoid-bugs/">this post</a> from Kent C. Dodds or <a target="_blank" href="https://overreacted.io/making-setinterval-declarative-with-react-hooks/">this post</a> from Dan Abramov to learn more about the role that closures play in React.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Scope refers to the part of a program where we can access a variable. JavaScript allows us to nest scopes, and variables declared in outer scopes are accessible from all inner ones. Variables can be globally-, module-, or block-scoped.</p>
<p>A closure is a function enclosed with references to the variables in its outer scope. Closures allow functions to maintain connections with outer variables, even outside the scope of the variables. </p>
<p>There are many uses of closures, from creating class-like structures that store state and implement private methods to passing callbacks to event handlers.</p>
<h2 id="heading-lets-connect">Let's connect</h2>
<p>If you’re interested in more articles like this, <a target="_blank" href="https://mailchi.mp/2df4b6d5458f/signup-page">subscribe to my newsletter</a> and connect with me on <a target="_blank" href="https://www.linkedin.com/in/zach-snoek-5b327b179/">LinkedIn</a> and <a target="_blank" href="https://twitter.com/zach_snoek">Twitter</a>!</p>
<h2 id="heading-acknowledgements">Acknowledgements</h2>
<p>Thanks to <a target="_blank" href="https://github.com/bryanrsmith">Bryan Smith</a> for providing feedback on drafts of this post.</p>
<p>Cover photo by <a target="_blank" href="https://unsplash.com/@kar111?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Karine Avetisyan</a> on <a target="_blank" href="https://unsplash.com/s/photos/chain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Closure Tutorial – How Closures and Lexical Scope Work in JS ]]>
                </title>
                <description>
                    <![CDATA[ By Dave Gray In JavaScript, people often confuse closures with lexical scope. Lexical scope is an important part of closures, but it is not a closure by itself. Closures are an advanced concept that is also a frequent topic of technical interviews. Y... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-closure-lexical-scope/</link>
                <guid isPermaLink="false">66d45e0d230dff01669057cd</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Lexical Scoping ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 28 Jun 2021 18:45:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/06/tim-evans-Uf-c4u1usFQ-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dave Gray</p>
<p>In JavaScript, people often confuse closures with lexical scope.</p>
<p>Lexical scope is an important part of closures, but it is not a closure by itself.</p>
<p>Closures are an advanced concept that is also a frequent topic of technical interviews.</p>
<p>You should have a foundational understanding of functions before attempting to understand closures.</p>
<p>After reading this article, I hope I will have helped you learn the following:</p>
<ul>
<li>The difference between lexical scope and closures.</li>
<li>Why closures require lexical scope.</li>
<li>How to give an example of a closure during the interview process.</li>
</ul>
<h2 id="heading-what-is-lexical-scope-in-javascript">What is Lexical Scope in JavaScript?</h2>
<p>Lexical scope describes how nested (also known as "child") functions have access to variables defined in parent scopes.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFunction = <span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">let</span> myValue = <span class="hljs-number">2</span>;
     <span class="hljs-built_in">console</span>.log(myValue);

     <span class="hljs-keyword">const</span> childFunction = <span class="hljs-function">() =&gt;</span> {
          <span class="hljs-built_in">console</span>.log(myValue += <span class="hljs-number">1</span>);
     }

     childFunction();
}

myFunction();
</code></pre>
<p>In this example, <code>childFunction</code> has access to the variable <code>myValue</code> which is defined in the parent scope of <code>myFunction</code>. </p>
<p>The lexical scope of <code>childFunction</code> allows access to the parent scope.</p>
<h2 id="heading-what-is-a-closure-in-javascript">What is a Closure in JavaScript?</h2>
<p><a target="_blank" href="https://www.w3schools.com/js/js_function_closures.asp">w3Schools.com</a> offers a great definition of what a closure is:</p>
<blockquote>
<p>A closure is a function having access to the parent scope, even after the parent function has closed.</p>
</blockquote>
<p>Let's note the first part of the sentence before the comma:</p>
<blockquote>
<p>...a function having access to the parent scope</p>
</blockquote>
<p>That's describing lexical scope!</p>
<p>But we need the second part of the definition to give an example of a closure...</p>
<blockquote>
<p>...even after the parent function has closed.</p>
</blockquote>
<p>Let's look at an example of a closure:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFunction = <span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">let</span> myValue = <span class="hljs-number">2</span>;
     <span class="hljs-built_in">console</span>.log(myValue);

     <span class="hljs-keyword">const</span> childFunction = <span class="hljs-function">() =&gt;</span> {
          <span class="hljs-built_in">console</span>.log(myValue += <span class="hljs-number">1</span>);
     }

     <span class="hljs-keyword">return</span> childFunction;
}

<span class="hljs-keyword">const</span> result = myFunction();
<span class="hljs-built_in">console</span>.log(result);
result();
result();
result();
</code></pre>
<p>Copy the example code above and try it out.</p>
<p><em>Let's break down what is happening...</em></p>
<p>In this revision, <code>myFunction</code> returns <code>childFunction</code> instead of calling it.</p>
<p>Therefore, when <code>result</code> is set equal to <code>myFunction()</code>, the console statement inside <code>myFunction</code> is logged, but not the statement inside <code>childFunction</code>. </p>
<p><code>childFunction</code> is not called into action. </p>
<p>Instead, it is returned and held in <code>result</code>.</p>
<p>In addition, we need to realize that <code>myFunction</code> has closed after it was called.</p>
<p>The line with <code>console.log(result)</code> should show in the console that <code>result</code> now holds the anonymous function value that was <code>childFunction</code>.</p>
<p>Now, when we call <code>result()</code>, we are calling the anonymous function that was assigned to <code>childFunction</code>.</p>
<p>As a child of <code>myFunction</code>, this anonymous function has access to the <code>myValue</code> variable inside <code>myFunction</code> <em>even after it has closed!</em></p>
<p>The closure we created now allows us to continue to increase the value of the <code>myValue</code> variable every time we call <code>result()</code>.</p>
<h2 id="heading-take-your-time-with-closures">Take Your Time with Closures</h2>
<p>Closures are considered to be an advanced concept for good reason.</p>
<p>Even with a step-by-step breakdown of what a closure is, this concept can take time to understand.</p>
<p>Don't rush your understanding and don't be hard on yourself if it doesn't make sense at first.</p>
<p>When you fully understand closure, you may feel like <a target="_blank" href="https://www.google.com/search?q=neo+sees+the+matrix&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=2ahUKEwiG1MaN1rPxAhUNCM0KHQJWCtAQ_AUoAXoECAEQAw&amp;biw=1762&amp;bih=886">Neo when he sees the Matrix</a>. You'll see new code possibilities and realize they were there all along!</p>
<p>I'll leave you with a tutorial on closures from <a target="_blank" href="https://www.youtube.com/davegrayteachescode">my YouTube channel</a>. I dive a little deeper and provide a few more examples of closures to build on the discussion in this article.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/1S8SBDhA7HA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Closures in JavaScript – A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ By Matías Hernández Closures are a confusing JavaScript concept to learn, because it's hard to see how they're actually used.  Unlike other concepts such as functions, variables, and objects, you don't always use closures conscientiously and directly... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/closures-in-javascript/</link>
                <guid isPermaLink="false">66d46012246e57ac83a2c789</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Closure with example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 07 Jun 2021 18:18:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/English-Header-4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Matías Hernández</p>
<p>Closures are a confusing JavaScript concept to learn, because it's hard to see how they're actually used. </p>
<p>Unlike other concepts such as functions, variables, and objects, you don't always use closures conscientiously and directly. You don't say: Oh! Here I will use a closure as a solution.</p>
<p>But at the same time, you might have already used this concept a hundred times. Learning about closures is more about identifying when one is being used rather than learning a new concept.</p>
<h2 id="heading-what-is-a-closure-in-javascript">What is a closure in JavaScript?</h2>
<p>You have a closure when a function reads or modifies the value of a variable defined outside its context.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> value = <span class="hljs-number">1</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> data = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>]
    <span class="hljs-keyword">return</span> data.filter(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item % value === <span class="hljs-number">0</span>)
}
</code></pre>
<p>Here the function <code>doSomething</code> uses the variable <code>value</code>. But also the function <code>item =&gt; item % value === 0</code> can then be written like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
    <span class="hljs-keyword">return</span> item % value === <span class="hljs-number">0</span>
}
</code></pre>
<p>You use the value of the variable <code>value</code> that was defined outside of the function itself.</p>
<h2 id="heading-functions-can-access-values-out-of-context">Functions can access values out of context</h2>
<p>As in the previous example, a function can access and use values that are defined outside its "body" or context, for example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(count)
}
counter() <span class="hljs-comment">// print 1</span>
count = <span class="hljs-number">2</span>
counter() <span class="hljs-comment">// print 2</span>
</code></pre>
<p>This allows us to modify the value of the <code>count</code> variable from anywhere in the module. Then when the counter function is called, it will know how to use the current value.</p>
<h2 id="heading-why-do-we-use-functions"><strong>Why do we use functions?</strong></h2>
<p>But why do we use functions in our programs? Certainly it is possible – difficult, but possible – to write a program without using functions we define. So why do we create proper functions?</p>
<p>Imagine a piece of code that does something wonderful, whatever, and is made up of X number of lines.</p>
<pre><code><span class="hljs-comment">/* My wonderful piece of code */</span>
</code></pre><p>Now suppose you must use this <strong>wonderful piece of code</strong> in various parts of your program, what would you do?.</p>
<p>The "natural" option is to put this piece of code together into a set that can be reusable, and that reusable set is what we call a function. Functions are the best way to reuse and share code within a program.</p>
<p>Now, you can use your function as many times as possible. And, ignoring some particular cases, calling your function N times is the same as writing that <strong>wonderful piece of code</strong> N times. It is a simple replacement.</p>
<h2 id="heading-but-where-is-the-closure"><strong>But where is the closure?</strong></h2>
<p>Using the counter example, let's consider that as the <strong>wonderful piece of code.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(count)
}
counter() <span class="hljs-comment">// print 1</span>
</code></pre>
<p>Now, we want to reuse it in many parts, so we will "wrap" it in a function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wonderfulFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(count)
    }
    counter() <span class="hljs-comment">// print 1</span>
}
</code></pre>
<p>Now what do we have? A function: <code>counter</code> that uses a value that was declared outside it <code>count</code>. And a value: <code>count</code> that was declared in the <code>wonderfulFunction</code> function scope but that is used inside the <code>counter</code> function.</p>
<p>That is, we have a function that uses a value that was declared outside its context: <strong>a closure</strong>.</p>
<p>Simple, isn't it? Now, what happens when the function <code>wonderfulFunction</code> is executed? What happens to the variable <code>count</code> and the function <code>counter</code> once the <strong>parent</strong> function is executed? </p>
<p>The variables and functions declared in its body <em>"disappear"</em> (garbage collector).</p>
<p>Now, let's modify the example a bit:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wonderfulFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
        count++
        <span class="hljs-built_in">console</span>.log(count)
    }
   <span class="hljs-built_in">setInterval</span>(counter, <span class="hljs-number">2000</span>)
}
wonderfulFunction()
</code></pre>
<p>What will happen now to the variable and function declared inside <code>wonderfulFunction</code>? </p>
<p>In this example, we tell the browser to run <code>counter</code> every 2 seconds. So the JavaScript engine must keep a reference to the function and also to the variable that is used by it. Even after the parent function <code>wonderfulFunction</code> finishes its execution cycle, the function <code>counter</code> and the value count will still "<em>live"</em>.</p>
<p>This "effect" of having closures occurs because JavaScript supports the nesting of functions. Or in other words, functions are <strong>first class citizens</strong> in the language and you can use them like any other object: nested, passed as an argument, as a value of return, and so on.</p>
<h2 id="heading-what-can-i-do-with-closures-in-javascript"><strong>What can I do with closures in JavaScript?</strong></h2>
<h3 id="heading-immediately-invoked-function-expression-iife"><strong>Immediately-invoked Function Expression (IIFE)</strong></h3>
<p>This is a technique that was used a lot in the ES5 days to implement the "module" design pattern (before this was natively supported). The idea is to "wrap" your module in a function that is immediately executed.</p>
<pre><code class="lang-javascript">(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">arg1, arg2</span>)</span>{
...
...
})(arg1, arg2)
</code></pre>
<p>This lets you use private variables that can only be used by the module itself within the function – that is, it's allowed to emulate the access modifiers.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> <span class="hljs-built_in">module</span> = (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">privateMethod</span> (<span class="hljs-params"></span>) </span>{
    }
    <span class="hljs-keyword">const</span> privateValue = <span class="hljs-string">"something"</span>
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">get</span>: privateValue,
      <span class="hljs-attr">set</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">v</span>) </span>{ privateValue = v }
    }
})()

<span class="hljs-keyword">var</span> x = <span class="hljs-built_in">module</span>()
x.get() <span class="hljs-comment">// "something"</span>
x.set(<span class="hljs-string">"Another value"</span>)
x.get() <span class="hljs-comment">// "Another Value"</span>
x.privateValue <span class="hljs-comment">//Error</span>
</code></pre>
<h3 id="heading-function-factory"><strong>Function Factory</strong></h3>
<p>Another design pattern implemented thanks to closures is the “Function Factory”. This is when functions create functions or objects, for example, a function that allows you to create user objects.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> createUser = <span class="hljs-function">(<span class="hljs-params">{ userName, avatar }</span>) =&gt;</span> ({
      <span class="hljs-attr">id</span>: createID(),
      userName,
      avatar,
      changeUserName (userName) {
        <span class="hljs-built_in">this</span>.userName = userName;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
      },
      changeAvatar (url) {
        <span class="hljs-comment">// execute some logic to retrieve avatar image</span>
        <span class="hljs-keyword">const</span> newAvatar = fetchAvatarFromUrl(url)
        <span class="hljs-built_in">this</span>.avatar = newAvatar
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>
      }
    });

        <span class="hljs-built_in">console</span>.log(createUser({ <span class="hljs-attr">userName</span>: <span class="hljs-string">'Bender'</span>, <span class="hljs-attr">avatar</span>: <span class="hljs-string">'bender.png'</span> }));

    {
      <span class="hljs-string">"id"</span>:<span class="hljs-string">"17hakg9a7jas"</span>,
      <span class="hljs-string">"avatar"</span>: <span class="hljs-string">"bender.png"</span>,
      <span class="hljs-string">"userName"</span>: <span class="hljs-string">"Bender"</span>,
      <span class="hljs-string">"changeUsername"</span>: [<span class="hljs-built_in">Function</span> changeUsername]
      <span class="hljs-string">"changeAvatar"</span>: [<span class="hljs-built_in">Function</span> changeAvatar]

    }
    */c
</code></pre>
<p>And using this pattern you can implement an idea from functional programming called <strong>currying</strong>.</p>
<h3 id="heading-currying"><strong>Currying</strong></h3>
<p>Currying is a design pattern (and a characteristic of some languages) where a function is immediately evaluated and returns a second function. This pattern lets you execute specialization and composition.</p>
<p>You create these "curried" functions using closures, defining and returning the inner function of the closure.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">a</span>) </span>{

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">b</span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">c</span>)  </span>{
            <span class="hljs-keyword">return</span> a * b * c
        }
    }
}
<span class="hljs-keyword">let</span> mc1 = multiply(<span class="hljs-number">1</span>);
<span class="hljs-keyword">let</span> mc2 = mc1(<span class="hljs-number">2</span>);
<span class="hljs-keyword">let</span> res = mc2(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(res);

<span class="hljs-keyword">let</span> res2 = multiply(<span class="hljs-number">1</span>)(<span class="hljs-number">2</span>)(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(res2);
</code></pre>
<p>These types of functions take a single value or argument and return another function that also receives an argument. It is a partial application of the arguments. It is also possible to rewrite this example using ES6.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> multiply = <span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">b</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">c</span>) =&gt;</span> {

    <span class="hljs-keyword">return</span> a * b * c;
}

<span class="hljs-keyword">let</span> mc1 = multiply(<span class="hljs-number">1</span>);
<span class="hljs-keyword">let</span> mc2 = mc1(<span class="hljs-number">2</span>);
<span class="hljs-keyword">let</span> res = mc2(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(res);

<span class="hljs-keyword">let</span> res2 = multiply(<span class="hljs-number">1</span>)(<span class="hljs-number">2</span>)(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(res2);
</code></pre>
<p>Where can we apply currying? In composition, let's say you have a function that creates HTML elements.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createElement</span>(<span class="hljs-params">element</span>)</span>{
    <span class="hljs-keyword">const</span> el = <span class="hljs-built_in">document</span>.createElement(element)
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">content</span>) </span>{
        <span class="hljs-keyword">return</span> el.textNode = content
    }
}

<span class="hljs-keyword">const</span> bold = crearElement(<span class="hljs-string">'b'</span>)
<span class="hljs-keyword">const</span> italic = createElement(<span class="hljs-string">'i'</span>)
<span class="hljs-keyword">const</span> content = <span class="hljs-string">'My content'</span>
<span class="hljs-keyword">const</span> myElement  = bold(italic(content)) <span class="hljs-comment">// &lt;b&gt;&lt;i&gt;My content&lt;/i&gt;&lt;/b&gt;</span>
</code></pre>
<h3 id="heading-event-listeners"><strong>Event Listeners</strong></h3>
<p>Another place you can use and apply closures is in event handlers using React. </p>
<p>Suppose you are using a third party library to render the items in your data collection. This library exposes a component called <code>RenderItem</code> that has only one available prop <code>onClick</code>. This prop does not receive any parameters and does not return a value. </p>
<p>Now, in your particular app, you require that when a user clicks on the item the app displays an alert with the item's title. But the <code>onClick</code> event that you have available does not accept arguments – so what can you do? <strong>Closures to the rescue</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Closure</span>
<span class="hljs-comment">// with es5</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onItemClick</span>(<span class="hljs-params">title</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      alert(<span class="hljs-string">"Clicked "</span> + title)
    }
}
<span class="hljs-comment">// with es6</span>
<span class="hljs-keyword">const</span> onItemClick = <span class="hljs-function"><span class="hljs-params">title</span> =&gt;</span> <span class="hljs-function">() =&gt;</span> alert(<span class="hljs-string">`Clcked <span class="hljs-subst">${title}</span>`</span>)

<span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Container</span>&gt;</span>
{items.map(item =&gt; {
return (
   <span class="hljs-tag">&lt;<span class="hljs-name">RenderItem</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onItemClick(item.title)}</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Title</span>&gt;</span>{item.title}<span class="hljs-tag">&lt;/<span class="hljs-name">Title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">RenderItem</span>&gt;</span>
)
})}
<span class="hljs-tag">&lt;/<span class="hljs-name">Container</span>&gt;</span></span>
)
</code></pre>
<p>In this simplified example we create a function that receives the title that you want to display and returns another function that meets the definition of the function that RenderItem receives as a prop.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>You can develop an app without even knowing that you are using closures. But knowing that they exist and how they really work unlocks new possibilities when you're creating a solution. </p>
<p>Closures are one of those concepts that can be hard to understand when you're starting out. But once you know you're using them and understand them, it allows you to increase your tools and advance your career.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/English-Footer-Social-Card-1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>🐦 <a target="_blank" href="https://twitter.com/matiasfha">Follow me on Twitter</a>           ✉️ <a target="_blank" href="https://matiashernandez.ck.page">Join to the newsletter</a>           ❤️ <a target="_blank" href="https://buymeacoffee.com/matiasfha">Support my work</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Why You Should Know JavaScript Closures ]]>
                </title>
                <description>
                    <![CDATA[ Fully understanding closures may seem like a right of passage to becoming a JavaScript developer.  There is a reason why it can be difficult to make sense of closures—because they are often taught backwards. You may have been taught what a closures i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-closures/</link>
                <guid isPermaLink="false">66d03799ccf811d3117aeedf</guid>
                
                    <category>
                        <![CDATA[ Closure with example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Tue, 09 Jun 2020 14:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/Why-JS-Closures-Matter.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Fully understanding closures may seem like a right of passage to becoming a JavaScript developer. </p>
<p>There is a reason why it can be difficult to make sense of closures—because they are often taught <em>backwards</em>. You may have been taught what a closures is, but you might not understand how they are useful to the average developer or within your own code.</p>
<p><strong>So why do closures matter in our day-to-day JavaScript code?</strong></p>
<p>Instead of seeing closures as a topic to be memorized for some sort of pop quiz, let's see what series of steps can lead us to seeing a closure in the first place. Once we see what they are, we will uncover why closures are worthwhile for you to know and take advantage of in your JavaScript code.</p>
<h2 id="heading-seeing-a-closure-in-the-wild">Seeing a closure in the wild ?</h2>
<p>Let's say we are making an app clone of the blogging site Medium, and we want each user to be able to like different posts.</p>
<p>Whenever a user clicks on the like button, its value will be incremented by one each time.</p>
<p>Think of it like the Medium clap button:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/react-clap-demo.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The function that will handle increasing the count by 1 each time is called <code>handleLikePost</code> and we are keeping track of the number of likes with a variable named <code>likeCount</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// global scope</span>
<span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// function scope</span>
  likeCount = likeCount + <span class="hljs-number">1</span>;
}

handleLikePost();
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"like count:"</span>, likeCount); <span class="hljs-comment">// like count: 1</span>
</code></pre>
<p>Whenever a user likes a post, we call <code>handleLikePost</code> and it increments our <code>likeCount</code> by 1.</p>
<p>And this works because we know that functions can access variables outside of themselves.</p>
<p>In other words, <strong>functions can access any variables defined in any parent scope</strong>.</p>
<p>There's a problem with this code, however. Since <code>likeCount</code> is in the global scope, and not in any function, <code>likeCount</code> is a global variable. Global variables can be used (and changed) by any other bit of code or function in our app.</p>
<p>For example, what if after our function, we mistakenly set our <code>likeCount</code> to 0?</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  likeCount = likeCount + <span class="hljs-number">1</span>;
}

handleLikePost();
likeCount = <span class="hljs-number">0</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"like count:"</span>, likeCount); <span class="hljs-comment">// like count: 0</span>
</code></pre>
<p>Naturally, <code>likeCount</code> can never be incremented from 0.</p>
<p>When only one function needs a given piece of data, it just needs to exist locally, that is, within that function.</p>
<p>Now let's bring <code>likeCount</code> within our function:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// likeCount moved from global scope to function scope</span>
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  likeCount = likeCount + <span class="hljs-number">1</span>;
}
</code></pre>
<p>Note that there's a shorter way to write the line where we increment <code>likeCount</code>. Instead of saying <code>likeCount</code> is equal to previous value of <code>likeCount</code> and add one like this, we can just use the += operator like so:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  likeCount += <span class="hljs-number">1</span>;
}
</code></pre>
<p>And for it to work as before and get like count's value, we also need to bring our <code>console.log</code> into the function as well.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  likeCount += <span class="hljs-number">1</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"like count:"</span>, likeCount);
}

handleLikePost(); <span class="hljs-comment">// like count: 1</span>
</code></pre>
<p>And it still works properly as before.</p>
<p>So now users should be able to like a post as many times as they want, so let's call <code>handleLikePost</code> a few more times:</p>
<pre><code class="lang-jsx">handleLikePost(); <span class="hljs-comment">// like count: 1</span>
handleLikePost(); <span class="hljs-comment">// like count: 1</span>
handleLikePost(); <span class="hljs-comment">// like count: 1</span>
</code></pre>
<p>When we run this code, however, there's a problem.</p>
<p>We would expect to see the <code>likeCount</code> keep increasing, but we just see 1 each time. Why is that?</p>
<p>Take a second, look at our code and try to explain why our <code>likeCount</code> is no longer being incremented.</p>
<p>Let's look at our <code>handleLikePost</code> function and how it's working:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  likeCount += <span class="hljs-number">1</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"like count:"</span>, likeCount);
}
</code></pre>
<p>Every time we use it, we are recreating this <code>likeCount</code> variable, which is given an initial value of 0.</p>
<p>No wonder we can't keep track of the count between function calls! It keeps being set to 0 each time, then it's incremented by 1, after which the function is finished running.</p>
<p>So we're stuck here. Our variable needs to live inside of the <code>handleLikePost</code> function, but we can't preserve the count.</p>
<p>We need something that allows us to preserve or remember the <code>likeCount</code> value between function calls.</p>
<p>What if we tried something that may look a little strange at first—what if we tried putting another function in our function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  likeCount += <span class="hljs-number">1</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{

  }
}

handleLikePost();
</code></pre>
<p>Here we're going to name this function <code>addLike</code>. The reason? Because it will be responsible for incrementing the <code>likeCount</code> variable now.</p>
<p>And note that this inner function doesn't have to have a name. It can be an anonymous function. In most cases, it is. We're just giving it a name so we can more easily talk about it and what it does.</p>
<p><code>addLike</code> will now be responsible for increasing our <code>likeCount</code>, so we'll move the line where we increment by 1 into our inner function.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += <span class="hljs-number">1</span>;
  }
}
</code></pre>
<p>What if we were to call this <code>addLike</code> function in <code>handleLikePost</code>?</p>
<p>All that would happen is that <code>addLike</code> would increment our <code>likeCount</code>, but still the <code>likeCount</code> variable would be destroyed. So again, we lose our value and the result is 0.</p>
<p>But instead of calling <code>addLike</code> within its enclosing function, what if we called it outside of the function? This seems even stranger. And how would we do that?</p>
<p>We know at this point that functions return values. For example, we could return our <code>likeCount</code> value at the end of <code>handleLikePost</code> to pass it to other parts of of our program:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += <span class="hljs-number">1</span>;
  }
  addLike();
  <span class="hljs-keyword">return</span> likeCount;
}
</code></pre>
<p>But instead of doing that, let's return <code>likeCount</code> within <code>addLike</code> and then return the <code>addLike</code> function itself:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> likeCount;
  };
  <span class="hljs-comment">// addLike();</span>
}

handleLikePost();
</code></pre>
<p>Now this may look bizarre, but this is allowed in JS. We can use functions like any other value in JS. That means a function can be returned from another function. By returning the inner function, we can call it from outside of its enclosing function.</p>
<p>But how would we do that? Think about this for a minute and see if you can figure it out...</p>
<p>First, to better see what's happening, let's <code>console.log(handleLikePost)</code> when we call it and see what we get:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> likeCount;
  };
}

<span class="hljs-built_in">console</span>.log(handleLikePost()); <span class="hljs-comment">// ƒ addLike()</span>
</code></pre>
<p>Unsurprisingly, we get the <code>addLike</code> function logged. Why? Because we're returning it, after all.</p>
<p>To call it, couldn't we just put it in another variable? As we just said, functions can be used like any other value in JS. If we can return it from a function, we can put it in a variable too. So let's put it in a new variable called <code>like</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> likeCount;
  };
}

<span class="hljs-keyword">const</span> like = handleLikePost();
</code></pre>
<p>And finally, let's call <code>like</code>. We'll do it a few times and <code>console.log</code> each result:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> likeCount;
  };
}

<span class="hljs-keyword">const</span> like = handleLikePost();

<span class="hljs-built_in">console</span>.log(like()); <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(like()); <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(like()); <span class="hljs-comment">// 3</span>
</code></pre>
<p>Our <code>likeCount</code> is finally preserved! Every time we call <code>like</code>, the <code>likeCount</code> is incremented from its previous value.</p>
<p>So what in the world happened here? Well, we figured out how to call the <code>addLike</code> function from outside the scope in which it was declared. We did that by returning the inner function from the outer one and storing a reference to it, named <code>like</code>, to call it.</p>
<h2 id="heading-how-a-closure-works-line-by-line">How a closure works, line-by-line ?</h2>
<p>So that was our implementation, of course, but how did we preserve the value of <code>likeCount</code> between function calls?</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> likeCount;
  };
}

<span class="hljs-keyword">const</span> like = handleLikePost();

<span class="hljs-built_in">console</span>.log(like()); <span class="hljs-comment">// 1</span>
</code></pre>
<ol>
<li>The <code>handleLikePost</code> outer function is executed, creating an instance of the inner function <code>addLike</code>; that function <em>closes</em> over the variable <code>likeCount</code>, which is one scope above.</li>
<li>We called the <code>addLike</code> function from outside the scope in which it was declared. We did that by returning the inner function from the outer one and storing a reference to it, named <code>like</code>, to call it.</li>
<li>When the <code>like</code> function finishes running, normally we would expect all of its variables to be garbage collected (removed from memory, which is an automatic process that the JS compiler does). We'd expect each <code>likeCount</code> to go away when the function is done, but they don't.</li>
</ol>
<p>What is that reason? <em>Closure</em>.</p>
<p><strong>Since the inner function instances are still alive (assigned to <code>like</code>), the closure is still preserving the <code>countLike</code> variables.</strong></p>
<p>You would think that having a function written in another function, would just be like a function written in the global scope. But it's not.</p>
<p><em>This is why closure makes functions so powerful</em>, because it is a special property that isn't present in anything else in the language.</p>
<h2 id="heading-the-lifetime-of-a-variable">The lifetime of a variable</h2>
<p>To better appreciate closures, we have to understand how JavaScript treats variables that are created. You might have wondered what happens to variables when you close your page or go to another page within an app. How long do variables live?</p>
<p>Global variables live until the program is discarded, for example when you close the window. They are around for the life of the program.</p>
<p>However, local variables have short lives. They are created when the function is invoked, and deleted when the function is finished.</p>
<p>So before, where <code>likeCount</code> was just a local variable, when the function was run. The likeCount variable was created at the beginning of the function and then destroyed once it finished executing.</p>
<h2 id="heading-closures-are-not-snapshots-they-keep-local-variables-alive">Closures are not snapshots - they keep local variables alive</h2>
<p>It's sometimes stated that JavaScript closures are similar to snapshots, a picture of our program at certain point in time. This is a misconception that we can dispel by adding another feature to our like button functionality.</p>
<p>Let's say that on some rare occasions, we want to allow users to 'double like' a post and increment the <code>likeCount</code> by 2 at a time instead of 1.</p>
<p>How would would we add this feature?</p>
<p>Another way to pass values to a function is of course through arguments, which operate just like local variables.</p>
<p>Let's pass in an argument called step to the function, which will allow us to provide a dynamic, changeable value to increment our count by instead of the hard-coded value 1.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params">step</span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += step;
    <span class="hljs-comment">// likeCount += 1;</span>
    <span class="hljs-keyword">return</span> likeCount;
  };
}
</code></pre>
<p>Next, let's try making a special function that will allow us to double like our posts, doubleLike. We'll pass in 2 as our <code>step</code> value to make it and then try calling both of our functions, <code>like</code> and <code>doubleLike</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleLikePost</span>(<span class="hljs-params">step</span>) </span>{
  <span class="hljs-keyword">let</span> likeCount = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addLike</span>(<span class="hljs-params"></span>) </span>{
    likeCount += step;
    <span class="hljs-keyword">return</span> likeCount;
  };
}

<span class="hljs-keyword">const</span> like = handleLikePost(<span class="hljs-number">1</span>);
<span class="hljs-keyword">const</span> doubleLike = handleLikePost(<span class="hljs-number">2</span>);

like(); <span class="hljs-comment">// 1</span>
like(); <span class="hljs-comment">// 2</span>

doubleLike(); <span class="hljs-comment">// 2 (the count is still being preserved!)</span>
doubleLike(); <span class="hljs-comment">// 4</span>
</code></pre>
<p>We see the <code>likeCount</code> is also being preserved for <code>doubleLike</code>.</p>
<p>What's happening here?</p>
<p>Each instance of the inner <code>addLike</code> function closes over both the <code>likeCount</code> and <code>step</code> variables from its outer <code>handleLikePost</code> function's scope. <code>step</code> remains the same over time, but the count is updated on each invocation of that inner function. Since closure is over the variables and not just snapshots of the values, these updates are preserved between function calls.</p>
<p>So what does this code show to us—the fact that we can pass in dynamic values to change the result of our function? That they are still alive! Closures keep local variables alive from functions that should have destroyed them a long time ago.</p>
<p>In other words, they are not static and unchanging, like a snapshot of the closed-over variables value at one point in time—closures preserve the variables and provide an active link to them. As a result, we can use closures can observe or make updates to these variables over time.</p>
<h2 id="heading-what-is-a-closure-exactly">What is a closure, exactly?</h2>
<p>Now that you see how a closure is useful, there are two criteria for something to be a closure, both of which you've seen here:</p>
<ol>
<li>Closures are a property of JavaScript functions, and only functions. No other data type has them.</li>
<li>To observe a closure, you must execute a function in a different scope than where that function was originally defined.</li>
</ol>
<h2 id="heading-why-should-you-know-closures">Why should you know closures?</h2>
<p>Let's answer the original question we set out to answer. Based off of what we've seen, pause and take a stab at answering this question. Why should we care about closures as JS developers?</p>
<p>Closures matter for you and your code because they allow you to 'remember' values, which is a very powerful and unique feature in the language which only functions possess.</p>
<p>We saw it right here in this example. After all, what use is a like count variable that doesn't remember likes? You'll encounter this often in your JS career. You need to hold onto some value somehow and likely keep it separate from other values. What do you use? A function. Why? To keep track of data over time with a closure.</p>
<p>And with that, you're already a step ahead other developers. </p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Closure Tutorial – With JS Closure Example Code ]]>
                </title>
                <description>
                    <![CDATA[ By Anchal Nigam Closures – many of you JavaScript devs have probably heard this term before. When I started my journey with JavaScript, I encountered closures often. And I think they're one of the most important and interesting concepts in JavaScript... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-closure-tutorial-with-js-closure-example-code/</link>
                <guid isPermaLink="false">66d45d9ba44b8bb91150f655</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Closure with example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Lexical Scoping ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 27 May 2020 07:07:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/closure-1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Anchal Nigam</p>
<p><strong>Closures –</strong> many of you JavaScript devs have probably heard this term before. When I started my journey with JavaScript, I encountered closures often. And I think they're one of the most important and interesting concepts in JavaScript. </p>
<p>You don't think they're interesting? This often happens when you don’t understand a concept – you don’t find it interesting. (I don’t know if this happens to you or not, but this is the case with me). </p>
<p>So in this article, I will try to make closures interesting for you.</p>
<p>Before going into the world of closures, let’s first understand <strong>lexical scoping</strong>. If you already know about it, skip the next part. Otherwise jump into it to better understand closures.</p>
<h2 id="heading-lexical-scoping">Lexical Scoping</h2>
<p>You may be thinking – I know local and global scope, but what the heck is lexical scope? I reacted the same way when I heard this term. Not to worry! Let’s take a closer look. </p>
<p>It’s simple like other two scopes:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> customerName = <span class="hljs-string">"anchal"</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetingMsg</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi! "</span> + customerName); <span class="hljs-comment">// Hi! anchal</span>
    }
   greetingMsg();
}
</code></pre>
<p>You can see from the above output that the inner function can access the outer function's variable. This is lexical scoping, where the scope and value of a variable is determined by where it is defined/created (that is, its position in the code). Got it? </p>
<p>I know that last bit might have confused you. So let me take you deeper. Did you know that lexical scoping is also known as <strong>static scoping</strong>? Yes, that's its other name. </p>
<p>There is also <strong>dynamic scoping</strong>, which some programming languages support. Why have I mentioned dynamic scoping? Because it can help you better understand lexical scoping.</p>
<p>Let’s look at some examples:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetingMsg</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(customerName);<span class="hljs-comment">// ReferenceError: customerName is not defined</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">var</span> customerName = <span class="hljs-string">"anchal"</span>;
   greetingMsg();
}

greetCustomer();
</code></pre>
<p>Do you agree with the output? Yes, it will give a reference error. This is because both functions don’t have access to each other’s scope, as they are defined separately.</p>
<p>Let’s look at another example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">number1</span>) </span>{
  <span class="hljs-built_in">console</span>.log(number1 + number2);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbersGenerate</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> number2 = <span class="hljs-number">10</span>;
  addNumbers(number2);
}

addNumbersGenerate();
</code></pre>
<p>The above output will be 20 for a dynamically scoped language. Languages that support lexical scoping will give <code>referenceError: number2 is not defined</code>. Why?</p>
<p>Because in dynamic scoping, searching takes place in the local function first, then it goes into the function that <em>called</em> that local function. Then it searches in the function that called <em>that</em> function, and so on, up the call stack. </p>
<p>Its name is self explanatory – “dynamic” means change. The scope and value of variable can be different as it depends on from where the function is called. The meaning of a variable can change at runtime. </p>
<p>Got the gist of dynamic scoping? If yes, then just remember that lexical scoping is its opposite.</p>
<p>In lexical scoping, searching takes place in the local function first, then it goes into the function inside which <em>that</em> function is defined. Then it searches in the function inside which <em>that</em> function is defined and so on. </p>
<p>So, <strong>lexical</strong> or <strong>static scoping</strong> means the scope and value of a variable is determined from where it is defined. It doesn’t change. </p>
<p>Let’s again look at the above example and try to figure out the output on your own. Just one twist – declare <code>number2</code> at the top:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> number2 = <span class="hljs-number">2</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">number1</span>) </span>{
  <span class="hljs-built_in">console</span>.log(number1 + number2);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbersGenerate</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> number2 = <span class="hljs-number">10</span>;
  addNumbers(number2);
}

addNumbersGenerate();
</code></pre>
<p>Do you know what the output will be? </p>
<p>Correct – it’s 12 for lexically scoped languages. This is because first, it looks into an <code>addNumbers</code> function (innermost scope) then it searches inwards, where this function is defined. As it gets the <code>number2</code> variable, meaning the output is 12.</p>
<p>You may be wondering why I have spent so much time on lexical scoping here. This is a closure article, not one about lexical scoping. But if you don’t know about lexical scoping then you will not understand closures. </p>
<p>Why? You will get your answer when we look at the definition of a closure. So let’s get into the track and get back to closures.</p>
<h2 id="heading-what-is-a-closure">What is a Closure?</h2>
<p>Let’s look at the definition of a closure:</p>
<blockquote>
<p>Closure is created when an inner function has access to its outer function variables and arguments. The inner function has access to –   </p>
<ol>
<li>Its own variables.  </li>
<li>Outer function's variables and arguments.  </li>
<li>Global variables.</li>
</ol>
</blockquote>
<p>Wait! Is this the definition of a closure or lexical scoping? Both definitions look the same. How they are different? </p>
<p>Well, that's why I defined lexical scoping above. Because closures are related to lexical/static scoping. </p>
<p>Let’s again look at its other definition that will tell you how closures are different.</p>
<blockquote>
<p>Closure is when a function is able to access its lexical scope, even when that function is executing outside its lexical scope.</p>
</blockquote>
<p>Or,</p>
<blockquote>
<p>Inner functions can access its parent scope, even after the parent function is already executed.</p>
</blockquote>
<p>Confused? Don't worry if you haven't yet gotten the point. I have examples to help you better understand. Let’s modify the first example of lexical scoping:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> customerName = <span class="hljs-string">"anchal"</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetingMsg</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi! "</span> + customerName);
  }
  <span class="hljs-keyword">return</span> greetingMsg;
}

<span class="hljs-keyword">const</span> callGreetCustomer = greetCustomer();
callGreetCustomer(); <span class="hljs-comment">// output – Hi! anchal</span>
</code></pre>
<p>The difference in this code is that we are returning the inner function and executing it later. In some programming languages, the local variable exists during the function’s execution. But once the function is executed, those local variables don’t exist and they will not be accessible. </p>
<p>Here, however, the scene is different. After the parent function is executed, the inner function (returned function) can still access the parent function's variables. Yes, you guessed right. Closures are the reason. </p>
<p>The inner function preserves its lexical scope when the parent function is executing and hence, later that inner function can access those variables. </p>
<p>To get a better feel for it, let’s use the <code>dir()</code> method of the console to look into the list of the properties of <code>callGreetCustomer</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(callGreetCustomer);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/closure.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>From the above image, you can see how the inner function preserves its parent scope (<code>customerName</code>) when <code>greetCustomer()</code> is executed. And later on, it used <code>customerName</code> when <code>callGreetCustomer()</code> was executed.</p>
<p>I hope this example helped you better understand the above definition of a closure. And maybe now you find closures a bit more fun. </p>
<p>So what next? Let’s make this topic more interesting by looking at different examples.</p>
<h2 id="heading-examples-of-closures-in-action">Examples of closures in action</h2>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> count++;
  };
}

<span class="hljs-keyword">const</span> countValue = counter();
countValue(); <span class="hljs-comment">// 0</span>
countValue(); <span class="hljs-comment">// 1</span>
countValue(); <span class="hljs-comment">// 2</span>
</code></pre>
<p>Every time you call <code>countValue</code>, the count variable value is incremented by 1. Wait – did you think that the value of count is 0? </p>
<p>Well, that would be wrong as a closure doesn’t work with a value. It stores the <strong>reference</strong> of the variable. That’s why, when we update the value, it reflects in the second or third call and so on as the closure stores the reference. </p>
<p>Feeling a bit clearer now? Let’s look at another example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> count++;
  };
}

<span class="hljs-keyword">const</span> countValue1 = counter();
<span class="hljs-keyword">const</span> countValue2 = counter();
countValue1();  <span class="hljs-comment">// 0</span>
countValue1();  <span class="hljs-comment">// 1</span>
countValue2();   <span class="hljs-comment">// 0</span>
countValue2();   <span class="hljs-comment">// 1</span>
</code></pre>
<p>I hope you guessed the right answer. If not, here is the reason. As <code>countValue1</code> and <code>countValue2</code>, both preserve their own lexical scope. They have independent lexical environments. You can use <code>dir()</code> to check the <code>[[scopes]]</code> value in both the cases.</p>
<p>Let’s look at a third example.</p>
<p>This one's a bit different. In it, we have to write a function to achieve the output:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> addNumberCall = addNumber(<span class="hljs-number">7</span>);
addNumberCall(<span class="hljs-number">8</span>) <span class="hljs-comment">// 15</span>
addNumberCall(<span class="hljs-number">6</span>) <span class="hljs-comment">// 13</span>
</code></pre>
<p>Simple. Use your newly-gained closure knowledge:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumber</span>(<span class="hljs-params">number1</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">number2</span>) </span>{
    <span class="hljs-keyword">return</span> number1 + number2;
  };
}
</code></pre>
<p>Now let’s look at some tricky examples:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">countTheNumber</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> arrToStore = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> x = <span class="hljs-number">0</span>; x &lt; <span class="hljs-number">9</span>; x++) {
    arrToStore[x] = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> x;
    };
  }
  <span class="hljs-keyword">return</span> arrToStore;
}

<span class="hljs-keyword">const</span> callInnerFunctions = countTheNumber();
callInnerFunctions[<span class="hljs-number">0</span>]() <span class="hljs-comment">// 9</span>
callInnerFunctions[<span class="hljs-number">1</span>]() <span class="hljs-comment">// 9</span>
</code></pre>
<p>Every array element that stores a function will give you an output of 9. Did you guess right? I hope so, but still let me tell you the reason. This is because of the closure's behavior. </p>
<p>The closure stores the <strong>reference</strong>, not the value. The first time the loop runs, the value of x is 0. Then the second time x is 1, and so on. Because the closure stores the reference, every time the loop runs it's changing the value of x. And at last, the value of x will be 9. So <code>callInnerFunctions[0]()</code> gives an output of 9. </p>
<p>But what if you want an output of 0 to 8? Simple! Use a closure. </p>
<p>Think about it before looking at the solution below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callTheNumber</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAllNumbers</span>(<span class="hljs-params">number</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> number;
    };
  }
  <span class="hljs-keyword">var</span> arrToStore = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> x = <span class="hljs-number">0</span>; x &lt; <span class="hljs-number">9</span>; x++) {
    arrToStore[x] = getAllNumbers(x);
  }
  <span class="hljs-keyword">return</span> arrToStore;
}

<span class="hljs-keyword">const</span> callInnerFunctions = callTheNumber();
<span class="hljs-built_in">console</span>.log(callInnerFunctions[<span class="hljs-number">0</span>]()); <span class="hljs-comment">// 0</span>
<span class="hljs-built_in">console</span>.log(callInnerFunctions[<span class="hljs-number">1</span>]()); <span class="hljs-comment">// 1</span>
</code></pre>
<p>Here, we have created separate scope for each iteration. You can use <code>console.dir(arrToStore)</code> to check the value of x in <code>[[scopes]]</code> for different array elements.</p>
<p>That’s it! I hope you can now say that you find closures interesting.</p>
<p>To read my other articles, check out my profile <a target="_blank" href="https://www.freecodecamp.org/news/author/anchal">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Closures in JavaScript Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ What are Closures? A closure is the combination of a function and the lexical environment (scope) within which that function was declared. Closures are a fundamental and powerful property of Javascript. This article discusses the ‘how’ and ‘why’ abou... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/closures-in-javascript-explained-with-examples/</link>
                <guid isPermaLink="false">66c34760a1d481faeda49b10</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 18 Feb 2020 23:14:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9c82740569d1a4ca32a5.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h1 id="heading-what-are-closures"><strong>What are Closures?</strong></h1>
<p>A closure is the combination of a function and the lexical environment (scope) within which that function was declared. Closures are a fundamental and powerful property of Javascript. This article discusses the ‘how’ and ‘why’ about Closures:</p>
<h3 id="heading-example"><strong>Example</strong></h3>
<pre><code class="lang-js"><span class="hljs-comment">//we have an outer function named walk and an inner function named fly</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">walk</span> (<span class="hljs-params"></span>)</span>{

  <span class="hljs-keyword">var</span> dist = <span class="hljs-string">'1780 feet'</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fly</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'At '</span>+dist);
  }

  <span class="hljs-keyword">return</span> fly;
}

<span class="hljs-keyword">var</span> flyFunc = walk(); <span class="hljs-comment">//calling walk returns the fly function which is being assigned to flyFunc</span>
<span class="hljs-comment">//you would expect that once the walk function above is run</span>
<span class="hljs-comment">//you would think that JavaScript has gotten rid of the 'dist' var</span>

flyFunc(); <span class="hljs-comment">//Logs out 'At 1780 feet'</span>
<span class="hljs-comment">//but you still can use the function as above </span>
<span class="hljs-comment">//this is the power of closures</span>
</code></pre>
<h3 id="heading-another-example"><strong>Another Example</strong></h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">by</span>(<span class="hljs-params">propName</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{
        <span class="hljs-keyword">return</span> a[propName] - b[propName];
    }
}

<span class="hljs-keyword">const</span> person1 = {<span class="hljs-attr">name</span>: <span class="hljs-string">'joe'</span>, <span class="hljs-attr">height</span>: <span class="hljs-number">72</span>};
<span class="hljs-keyword">const</span> person2 = {<span class="hljs-attr">name</span>: <span class="hljs-string">'rob'</span>, <span class="hljs-attr">height</span>: <span class="hljs-number">70</span>};
<span class="hljs-keyword">const</span> person3 = {<span class="hljs-attr">name</span>: <span class="hljs-string">'nicholas'</span>, <span class="hljs-attr">height</span>: <span class="hljs-number">66</span>};

<span class="hljs-keyword">const</span> arr_ = [person1, person2, person3];

<span class="hljs-keyword">const</span> arr_sorted = arr_.sort(by(<span class="hljs-string">'height'</span>)); <span class="hljs-comment">// [ { name: 'nicholas', height: 66 }, { name: 'rob', height: 70 },{ name: 'joe', height: 72 } ]</span>
</code></pre>
<p>The closure ‘remembers’ the environment in which it was created. This environment consists of any local variables that were in-scope at the time the closure was created.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outside</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">var</span> rememberedVar = num; <span class="hljs-comment">// In this example, rememberedVar is the lexical environment that the closure 'remembers'</span>
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inside</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">// This is the function which the closure 'remembers'</span>
    <span class="hljs-built_in">console</span>.log(rememberedVar)
  }
}

<span class="hljs-keyword">var</span> remember1 = outside(<span class="hljs-number">7</span>); <span class="hljs-comment">// remember1 is now a closure which contains rememberedVar = 7 in its lexical environment, and //the function 'inside'</span>
<span class="hljs-keyword">var</span> remember2 = outside(<span class="hljs-number">9</span>); <span class="hljs-comment">// remember2 is now a closure which contains rememberedVar = 9 in its lexical environment, and //the function 'inside'</span>

remember1(); <span class="hljs-comment">// This now executes the function 'inside' which console.logs(rememberedVar) =&gt; 7</span>
remember2(); <span class="hljs-comment">// This now executes the function 'inside' which console.logs(rememberedVar) =&gt; 9</span>
</code></pre>
<p>Closures are useful because they let you ‘remember’ data and then let you operate on that data through returned functions. This allows javascript to emulate private methods that are found in other programming languages. Private methods are useful for restricting access to code as well as managing your global namespace.</p>
<h2 id="heading-private-variables-and-methods">Private variables and methods</h2>
<p>Closures can also be used to encapsulate private data/methods. Take a look at this example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> bankAccount = <span class="hljs-function">(<span class="hljs-params">initialBalance</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> balance = initialBalance;

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">getBalance</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> balance;
    },
    <span class="hljs-attr">deposit</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">amount</span>) </span>{
      balance += amount;
      <span class="hljs-keyword">return</span> balance;
    },
  };
};

<span class="hljs-keyword">const</span> account = bankAccount(<span class="hljs-number">100</span>);

account.getBalance(); <span class="hljs-comment">// 100</span>
account.deposit(<span class="hljs-number">10</span>); <span class="hljs-comment">// 110</span>
</code></pre>
<p>In this example, we won’t be able to access <code>balance</code> from anywhere outside of the <code>bankAccount</code> function, which means we’ve just created a private variable. Where’s the closure? Well, think about what <code>bankAccount()</code> is returning. It actually returns an Object with a bunch of functions inside it, and yet when we call <code>account.getBalance()</code>, the function is able to “remember” its initial reference to <code>balance</code>. That is the power of the closure, where a function “remembers” its lexical scope (compile time scope), even when the function is executed outside that lexical scope.</p>
<h3 id="heading-emulating-block-scoped-variables">Emulating block-scoped variables.</h3>
<p>Javascript did not have a concept of block-scoped variables. Meaning that when defining a variable inside a forloop for example, this variable is visible from outside the forloop as well. So how can closures help us solve this problem ? Let’s take a look.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> funcs = [];

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++){
        funcs[i] = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'My value is '</span> + i);  <span class="hljs-comment">//creating three different functions with different param values.</span>
        }
    }

    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">3</span>; j++){
        funcs[j]();             <span class="hljs-comment">// My value is 3</span>
                                <span class="hljs-comment">// My value is 3</span>
                                <span class="hljs-comment">// My value is 3</span>
    }
</code></pre>
<p>Since the variable i does not have block-scope, it’s value within all three functions was updated with the loop counter and created malicious values. Closure can help us solve this issue by creating a snapshot of the environment the function was in when it was created, preserving its state.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> funcs = [];

    <span class="hljs-keyword">var</span> createFunction = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">val</span>)</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"My value: "</span> + val);};
    }

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
        funcs[i] = createFunction(i);
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">3</span>; j++) {
        funcs[j]();                 <span class="hljs-comment">// My value is 0</span>
                                    <span class="hljs-comment">// My value is 1</span>
                                    <span class="hljs-comment">// My value is 2</span>
    }
</code></pre>
<p>The late versions of javascript es6+ have a new keyword called let which can be used to give the variable a blockscope. There are also many functions (forEach) and entire libraries (lodash.js) that are dedicated to solve such problems as the ones explained above. They can certainly boost your productivity, however it remains extremely important to have knowledge of all these issues when attempting to create something big.</p>
<p>Closures have many special applications that are useful when creating large javascript programs.</p>
<ol>
<li>Emulating private variables or encapsulation</li>
<li>Making Asynchronous server side calls</li>
<li>Creating a block-scoped variable.</li>
</ol>
<h3 id="heading-emulating-private-variables">Emulating private variables.</h3>
<p>Unlike many other languages, Javascript does not have a mechanism which allows you to create encapsulated instance variables within an object. Having public instance variables can cause a lot of problems when building medium to large programs. However with closures, this problem can be mitigated.</p>
<p>Much like in the previous example, you can build functions which return object literals with methods that have access to the object’s local variables without exposing them. Thus, making them effectively private.</p>
<p>Closures can also help you manage your global namespace to avoid collisions with globally shared data. Usually all global variables are shared between all scripts in your project, which will definitely give you alot of trouble when building medium to large programs. That is why library and module authors use closures to hide an entire module’s methods and data. This is called the module pattern, it uses an immediately invoked function expression which exports only certain functionality to the outside world, significantly reducing the amount of global references.</p>
<p>Here’s a short sample of a module skeleton.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> myModule = (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) = </span>{
    <span class="hljs-keyword">let</span> privateVariable = <span class="hljs-string">'I am a private variable'</span>;

    <span class="hljs-keyword">let</span> method1 = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am method 1'</span>); };
    <span class="hljs-keyword">let</span> method2 = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am method 2, '</span>, privateVariable); };

    <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">method1</span>: method1,
        <span class="hljs-attr">method2</span>: method2
    }
}());

myModule.method1(); <span class="hljs-comment">// I am method 1</span>
myModule.method2(); <span class="hljs-comment">// I am method 2, I am a private variable</span>
</code></pre>
<p>Closures are useful for capturing new instances of private variables contained in the ‘remembered’ environment, and those variables can only be accessed through the returned function or methods.</p>
<h2 id="heading-vectors">Vectors</h2>
<p>A vector is perhaps the most simple type of collection in Clojure. You can think of it like an array in Javascript. Let’s define a simple vector:</p>
<pre><code class="lang-text">(def a-vector [1 2 3 4 5])
;; Alternatively, use the vector function:
(def another-vector (vector 1 2 3 4 5))
;; You can use commas to separate items, since Clojure treats them as whitespace.
(def comma-vector [1, 2, 3, 4, 5])
</code></pre>
<p>You’ll see that it uses square brackets, just like an array in JS. Since Clojure, like JS, is dynamically typed, vectors can hold elements of any type, including other vectors.</p>
<pre><code class="lang-text">(def mixed-type-vector [1 "foo" :bar ["spam" 22] #"^baz$"])
</code></pre>
<h3 id="heading-adding-items-to-a-vector">Adding items to a vector</h3>
<p>You can append items to a vector using <code>conj</code>. You can also prepend to a list using <code>into</code>, but note that <code>into</code> is intended for merging two vectors, so both its arguments must be vectors, and using <code>into</code> is slower than using <code>conj</code>.</p>
<pre><code class="lang-text">(time (conj [1 2] 3))
; =&gt; "Elapsed time: 0.032206 msecs"
;    [1 2 3]
(time (into [1] [2 3]))
; =&gt; "Elapsed time: 0.078499 msecs"
;    [1 2 3]
</code></pre>
<p><img src="https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2" alt=":rocket:" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://ideone.com/wBSUEd">IDEOne it!</a></p>
<h3 id="heading-retrieving-items-from-a-vector">Retrieving items from a vector</h3>
<p>You can retrieve items from a vector using <code>get</code>. This is equivalent to using bracket notation to access items in an array in many imperative languages. Items in a vector are 0-indexed, counting from the left.</p>
<pre><code class="lang-text">var arr = [1, 2, 3, 4, 5];
arr[0];
// =&gt; 1
</code></pre>
<p>In Clojure, this would be written like so:</p>
<pre><code class="lang-text">(def a-vector [1 2 3 4 5])
(get a-vector 0)
; =&gt; 1
</code></pre>
<p>You can also give <code>get</code> a default value, if you give it an index that isn’t in the array.</p>
<pre><code class="lang-text">;; the list doesn't have 2147483647 elements, so it'll return a string instead.
(get a-vector 2147483646 "sorry, not found!")
; =&gt; "sorry, not found!"
</code></pre>
<h3 id="heading-converting-other-collections-into-vectors">Converting other collections into vectors</h3>
<p>Non-vector data structures can be converted into vectors using the <code>vec</code> function. With hashmaps, this produces a 2D vector containing pairs of keys and values.</p>
<pre><code class="lang-text">(vec '(1 2 3 4 5))
; =&gt; [1 2 3 4 5]
(vec {:jack "black" :barry "white"})
; =&gt; [[:jack "black"] [:barry "white"]]
</code></pre>
<h3 id="heading-when-to-use-a-vector">When to use a vector?</h3>
<p>A vector should be used in almost all cases if you need a collection, because they have the shortest random-access times, which makes it easy to retrieve items from a vector. Note that vectors are ordered. If order doesn’t matter, it may be better to use a set. Also note that vectors are designed for appending items; if you need to prepend items, you might want to use a list.</p>
<h2 id="heading-more-info-on-closures">More info on Closures:</h2>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-closures-in-n-minutes/">Learn JavaScript closures in six minutes</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/a-basic-guide-to-closures-in-javascript-9fc8b7e3463e/">A basic guide to closures in JavaScript</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/closures-vuejs-higher-order-functions-emojipicker-f10d3c249a12/">Discover the power of closures in VueJS</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/javascript-closures-explained-by-mailing-a-package-4f23e9885039/">JavaScript closures explained by mailing a package</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A simple guide to help you understand closures in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Prashant Ram Closures in JavaScript are one of those concepts that many struggle to get their heads around. In the following article, I will explain in clear terms what a closure is, and I’ll drive the point home using simple code examples. What i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-closures-simplified-d0d23fa06ba4/</link>
                <guid isPermaLink="false">66c358d97ef110ecbf367b2c</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 16 Jan 2018 19:10:53 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*tKGo4CSTcfWAO6-dTsb03g.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Prashant Ram</p>
<p>Closures in JavaScript are one of those concepts that many struggle to get their heads around. In the following article, I will explain in clear terms what a closure is, and I’ll drive the point home using simple code examples.</p>
<h3 id="heading-what-is-a-closure">What is a closure?</h3>
<p>A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables — a scope chain.</p>
<p>The closure has three scope chains:</p>
<ul>
<li>it has access to its own scope — variables defined between its curly brackets</li>
<li>it has access to the outer function’s variables</li>
<li>it has access to the global variables</li>
</ul>
<p>To the uninitiated, this definition might seem like just a whole lot of jargon!</p>
<h3 id="heading-but-what-really-is-a-closure"><strong>But what really is a closure?</strong></h3>
<h4 id="heading-a-simple-closure">A Simple closure</h4>
<p>Let’s look at a simple closure example in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params"></span>) </span>{

   <span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params"></span>) </span>{

         <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>; 
         <span class="hljs-built_in">console</span>.log(a+b);
    }
   <span class="hljs-keyword">return</span> inner;
}
</code></pre>
<p>Here we have two functions:</p>
<ul>
<li>an outer function <code>outer</code> which has a variable <code>b</code>, and returns the <code>inner</code> function</li>
<li>an inner function <code>inner</code> which has its variable called <code>a</code>, and accesses an <code>outer</code> variable <code>b</code>, within its function body</li>
</ul>
<p>The scope of variable <code>b</code> is limited to the <code>outer</code> function, and the scope of variable <code>a</code> is limited to the <code>inner</code> function.</p>
<p>Let us now invoke the <code>outer()</code> function, and store the result of the <code>outer()</code> function in a variable <code>X</code>. Let us then invoke the <code>outer()</code> function a second time and store it in variable <code>Y</code>.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;
    <span class="hljs-built_in">console</span>.log(a + b);
  }
  <span class="hljs-keyword">return</span> inner;
}

<span class="hljs-keyword">var</span> X = outer(); <span class="hljs-comment">//outer() invoked the first time</span>
<span class="hljs-keyword">var</span> Y = outer(); <span class="hljs-comment">//outer() invoked the second time</span>
</code></pre>
<p>Let’s see step-by-step what happens when the <code>outer()</code> function is first invoked:</p>
<ol>
<li>Variable <code>b</code> is created, its scope is limited to the <code>outer()</code> function, and its value is set to <code>10</code>.</li>
<li>The next line is a function declaration, so nothing to execute.</li>
<li>On the last line, <code>return inner</code> looks for a variable called <code>inner</code>, finds that this variable <code>inner</code> is actually a function, and so returns the entire body of the function <code>inner</code>.<br>[Note that the <code>return</code> statement does not execute the inner function — a function is executed only when followed by <code>()</code> — , but rather the <code>return</code> statement returns the entire body of the function.]</li>
<li>The contents returned by the return statement are stored in <code>X</code>.<br>Thus, <code>X</code> will store the following:<br><code>function inner() {</code><br><code>var a=20;</code><br><code>console.log(a+b);</code><br><code>}</code></li>
<li>Function <code>outer()</code> finishes execution, and all variables within the scope of <code>outer()</code> now no longer exist.</li>
</ol>
<p>This last part is important to understand. Once a function completes its execution, any variables that were defined inside the function scope cease to exist.</p>
<p>The lifespan of a variable defined inside of a function is the lifespan of the function execution.</p>
<p>What this means is that in <code>console.log(a+b)</code>, the variable <code>b</code> exists only during the execution of the the <code>outer()</code> function. Once the <code>outer</code> function has finished execution, the variable <code>b</code> no longer exists.</p>
<p>When the function is executed the second time, the variables of the function are created again, and live only up until the function completes execution.</p>
<p>Thus, when <code>outer()</code> is invoked the second time:</p>
<ol>
<li>A new variable <code>b</code> is created, its scope is limited to the <code>outer()</code> function, and its value is set to <code>10</code>.</li>
<li>The next line is a function declaration, so nothing to execute.</li>
<li><code>return inner</code> returns the entire body of the function <code>inner</code>.</li>
<li>The contents returned by the return statement are stored in <code>Y</code>.</li>
<li>Function <code>outer()</code> finishes execution, and all variables within the scope of <code>outer()</code> now no longer exist.</li>
</ol>
<p>The important point here is that when the <code>outer()</code> function is invoked the second time, the variable <code>b</code> is created anew. Also, when the <code>outer()</code> function finishes execution the second time, this new variable <code>b</code> again ceases to exist.</p>
<p>This is the most important point to realize. The variables inside the functions only come into existence when the function is running, and cease to exist once the functions completes execution.</p>
<p>Now, let us return to our code example and look at <code>X</code> and <code>Y</code>. Since the <code>outer()</code> function on execution returns a function, the variables <code>X</code> and <code>Y</code> are functions.</p>
<p>This can be easily verified by adding the following to the JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span>(X)); <span class="hljs-comment">//X is of type function</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span>(Y)); <span class="hljs-comment">//Y is of type function</span>
</code></pre>
<p>Since the variables <code>X</code> and <code>Y</code> are functions, we can execute them. In JavaScript, a function can be executed by adding <code>()</code> after the function name, such as <code>X()</code> and <code>Y()</code>.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params"></span>) </span>{

<span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params"></span>) </span>{

         <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>; 
         <span class="hljs-built_in">console</span>.log(a+b);
    }
   <span class="hljs-keyword">return</span> inner;
}

<span class="hljs-keyword">var</span> X = outer(); 
<span class="hljs-keyword">var</span> Y = outer(); 
<span class="hljs-comment">//end of outer() function executions</span>

X(); <span class="hljs-comment">// X() invoked the first time</span>
X(); <span class="hljs-comment">// X() invoked the second time</span>
X(); <span class="hljs-comment">// X() invoked the third time</span>

Y(); <span class="hljs-comment">// Y() invoked the first time</span>
</code></pre>
<p>When we execute <code>X()</code> and <code>Y()</code>, we are essentially executing the <code>inner</code> function.</p>
<p>Let us examine step-by-step what happens when <code>X()</code> is executed the first time:</p>
<ol>
<li>Variable <code>a</code> is created, and its value is set to <code>20</code>.</li>
<li>JavaScript now tries to execute <code>a + b</code>. Here is where things get interesting. JavaScript knows that <code>a</code> exists since it just created it. However, variable <code>b</code> no longer exists. Since <code>b</code> is part of the outer function, <code>b</code> would only exist while the <code>outer()</code> function is in execution. Since the <code>outer()</code> function finished execution long before we invoked <code>X()</code>, any variables within the scope of the <code>outer</code> function cease to exist, and hence variable <code>b</code> no longer exists.</li>
</ol>
<p>How does JavaScript handle this?</p>
<h4 id="heading-closures"><em>Closures</em></h4>
<p>The <code>inner</code> function can access the variables of the enclosing function due to closures in JavaScript. In other words, the <code>inner</code> function preserves the scope chain of the enclosing function at the time the enclosing function was executed, and thus can access the enclosing function’s variables.</p>
<p>In our example, the <code>inner</code> function had preserved the value of <code>b=10</code> when the <code>outer()</code> function was executed, and continued to preserve (closure) it.</p>
<p>It now refers to its scope chain and notices that it does have the value of variable <code>b</code> within its scope chain, since it had enclosed the value of <code>b</code> within a closure at the point when the <code>outer</code> function had executed.</p>
<p>Thus, JavaScript knows <code>a=20</code> and <code>b=10</code>, and can calculate <code>a+b</code>.</p>
<p>You can verify this by adding the following line of code to the example above:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;
    <span class="hljs-built_in">console</span>.log(a + b);
  }
  <span class="hljs-keyword">return</span> inner;
}

<span class="hljs-keyword">var</span> X = outer();

<span class="hljs-built_in">console</span>.dir(X); <span class="hljs-comment">//use console.dir() instead of console.log()</span>
</code></pre>
<p>Open the Inspect element in Google Chrome and go to the Console. You can expand the element to actually see the <code>Closure</code> element (shown in the third to last line below). Notice that the value of <code>b=10</code> is preserved in the <code>Closure</code> even after the <code>outer()</code> function completes its execution.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/VBcoedHEMM5cpIF4A1yTVFxTEn6ZzgYvTAGW" alt="Image" width="689" height="285" loading="lazy">
<em>Variable b=10 is preserved in the Closure, Closures in Javascript</em></p>
<p>Let us now revisit the definition of closures that we saw at the beginning and see if it now makes more sense.</p>
<p>So the inner function has three scope chains:</p>
<ul>
<li>access to its own scope — variable <code>a</code></li>
<li>access to the <code>outer</code> function’s variables — variable <code>b</code>, which it enclosed</li>
<li>access to any global variables that may be defined</li>
</ul>
<h3 id="heading-closures-in-action">Closures in Action</h3>
<p>To drive home the point of closures, let’s augment the example by adding three lines of code:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">var</span> b = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">var</span> c = <span class="hljs-number">100</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"a= "</span> + a + <span class="hljs-string">" b= "</span> + b);

    a++;
    b++;

  }
  <span class="hljs-keyword">return</span> inner;
}

<span class="hljs-keyword">var</span> X = outer(); <span class="hljs-comment">// outer() invoked the first time</span>
<span class="hljs-keyword">var</span> Y = outer();  <span class="hljs-comment">// outer() invoked the second time</span>
<span class="hljs-comment">//end of outer() function executions</span>

X(); <span class="hljs-comment">// X() invoked the first time</span>
X(); <span class="hljs-comment">// X() invoked the second time</span>
X(); <span class="hljs-comment">// X() invoked the third time</span>

Y(); <span class="hljs-comment">// Y() invoked the first time</span>
</code></pre>
<p>When you run this code, you will see the following output in the <code>console.log</code>:</p>
<pre><code>a=<span class="hljs-number">20</span> b=<span class="hljs-number">10</span>
a=<span class="hljs-number">20</span> b=<span class="hljs-number">11</span>
a=<span class="hljs-number">20</span> b=<span class="hljs-number">12</span>
a=<span class="hljs-number">20</span> b=<span class="hljs-number">10</span>
</code></pre><p>Let’s examine this code step-by-step to see what exactly is happening and to see closures in Action!</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> X = outer();  <span class="hljs-comment">// outer() invoked the first time</span>
</code></pre>
<p>The function <code>outer()</code> is invoked the first time. The following steps take place:</p>
<ol>
<li>Variable <code>b</code> is created, and is set to <code>10</code><br>Variable <code>c</code> is created, and set to <code>100</code><br>Let’s call this <code>b(first_time)</code> and <code>c(first_time)</code> for our own reference.</li>
<li>The <code>inner</code> function is returned and assigned to <code>X</code><br>At this point, the variable <code>b</code> is enclosed within the <code>inner</code> function scope chain as a closure with <code>b=10</code>, since <code>inner</code> uses the variable <code>b</code>.</li>
<li>The <code>outer</code> function completes execution, and all its variables cease to exist. The variable <code>c</code> no longer exists, although the variable <code>b</code> exists as a closure within <code>inner</code>.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> Y= outer();  <span class="hljs-comment">// outer() invoked the second time</span>
</code></pre>
<ol>
<li>Variable <code>b</code> is created anew and is set to <code>10</code><br>Variable <code>c</code> is created anew.<br>Note that even though <code>outer()</code> was executed once before variables <code>b</code> and <code>c</code> ceased to exist, once the function completed execution they are created as brand new variables.<br>Let us call these <code>b(second_time)</code> and <code>c(second_time)</code> for our own reference.</li>
<li>The <code>inner</code> function is returned and assigned to <code>Y</code><br>At this point the variable <code>b</code> is enclosed within the <code>inner</code> function scope chain as a closure with <code>b(second_time)=10</code>, since <code>inner</code> uses the variable <code>b</code>.</li>
<li>The <code>outer</code> function completes execution, and all its variables cease to exist.<br>The variable <code>c(second_time)</code> no longer exists, although the variable <code>b(second_time)</code> exists as closure within <code>inner</code>.</li>
</ol>
<p>Now let’s see what happens when the following lines of code are executed:</p>
<pre><code class="lang-js">X(); <span class="hljs-comment">// X() invoked the first time</span>
X(); <span class="hljs-comment">// X() invoked the second time</span>
X(); <span class="hljs-comment">// X() invoked the third time</span>

Y(); <span class="hljs-comment">// Y() invoked the first time</span>
</code></pre>
<p>When <code>X()</code> is invoked the first time,</p>
<ol>
<li>variable <code>a</code> is created, and set to <code>20</code></li>
<li>the value of <code>a=20</code>, the value of <code>b</code> is from the closure value. <code>b(first_time)</code>, so <code>b=10</code></li>
<li>variables <code>a</code> and <code>b</code> are incremented by <code>1</code></li>
<li><code>X()</code> completes execution and all its inner variables — variable <code>a</code> — cease to exist.<br>However, <code>b(first_time)</code> was preserved as the closure, so <code>b(first_time)</code> continues to exist.</li>
</ol>
<p>When <code>X()</code> is invoked the second time,</p>
<ol>
<li>variable <code>a</code> is created anew, and set to <code>20</code><br>Any previous value of variable <code>a</code> no longer exists, since it ceased to exists when <code>X()</code> completed execution the first time.</li>
<li>the value of <code>a=20</code><br>the value of <code>b</code> is taken from the closure value — <code>b(first_time)</code><br>Also note that we had incremented the value of <code>b</code> by <code>1</code> from the previous execution, so <code>b=11</code></li>
<li>variables <code>a</code> and <code>b</code> are incremented by <code>1</code> again</li>
<li><code>X()</code> completes execution and all its inner variables — variable a — cease to exist<br>However, <code>b(first_time)</code> is preserved as the closure continues to exist.</li>
</ol>
<p>When <code>X()</code> is invoked the third time,</p>
<ol>
<li>variable <code>a</code> is created anew, and set to <code>20</code><br>Any previous value of variable <code>a</code> no longer exists, since it ceased to exist when <code>X()</code> completed execution the first time.</li>
<li>the value of <code>a=20</code>, the value of <code>b</code> is from the closure value — <code>b(first_time)</code><br>Also note that we had incremented the value of <code>b</code> by <code>1</code> in the previous execution, so <code>b=12</code></li>
<li>variables <code>a</code> and <code>b</code> are incremented by <code>1</code> again</li>
<li><code>X()</code> completes execution, and all its inner variables — variable <code>a</code> — cease to exist<br>However, <code>b(first_time)</code> is preserved as the closure continues to exist</li>
</ol>
<p>When Y() is invoked the first time,</p>
<ol>
<li>variable <code>a</code> is created anew, and set to <code>20</code></li>
<li>the value of <code>a=20</code>, the value of <code>b</code> is from the closure value — <code>b(second_time)</code>, so <code>b=10</code></li>
<li>variables <code>a</code> and <code>b</code> are incremented by <code>1</code></li>
<li><code>Y()</code> completes execution, and all its inner variables — variable <code>a</code> — cease to exist<br>However, <code>b(second_time)</code> was preserved as the closure, so <code>b(second_time)</code> continues to exist.</li>
</ol>
<h3 id="heading-concluding-remarks">Concluding Remarks</h3>
<p>Closures are one of those subtle concepts in JavaScript that are difficult to grasp at first. But once you understand them, you realize that things could not have been any other way.</p>
<p>Hopefully these step-by-step explanations helped you really understand the concept of closures in JavaScript!</p>
<p><strong>Other Articles:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/promises-in-javascript-explained-277b98850de/">How to use Promises in JavaScript</a></li>
<li><a target="_blank" href="https://medium.com/@prashantramnyc/how-to-build-a-simple-sprite-animation-in-javascript-b764644244aa">How to build a simple Sprite animation in JavaScript</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
