<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://closurejsbyazeezjim.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 31 Aug 2026 13:03:10 GMT</lastBuildDate><atom:link href="https://closurejsbyazeezjim.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Closure In JavaScript]]></title><description><![CDATA[What is closure?
Closure is a fundamental concept in JavaScript, which enables functions to remember and access their lexical scope even when they are executed outside of that scope. It occurs when a function retains access to variables from its oute...]]></description><link>https://closurejsbyazeezjim.hashnode.dev/closure-in-javascript</link><guid isPermaLink="true">https://closurejsbyazeezjim.hashnode.dev/closure-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[closure]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Technical writing ]]></category><dc:creator><![CDATA[Garuba Abdul Azeez]]></dc:creator><pubDate>Mon, 26 Feb 2024 14:34:47 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1708968398564/c18b8428-acdd-4747-8361-51fa3924c695.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-what-is-closure">What is closure?</h3>
<p>Closure is a fundamental concept in JavaScript, which enables functions to remember and access their <strong>lexical scope</strong> even when they are executed outside of that scope. It occurs when a function retains access to variables from its outer scope even after the outer scope has <strong>finished executing</strong>.</p>
<h3 id="heading-lets-understand-two-vital-concepts">Let's understand two vital concepts.</h3>
<p>1: What is lexical scope?<br />2: What does it mean for a parent function to have finished expecting?</p>
<p><strong>Let's understand lexical scope with examples</strong></p>
<p><strong>Lexical scope</strong> defines how variable names are resolved in nested functions.</p>
<p>Imagine you have a set of nesting dolls. Each doll is placed inside another. The smaller doll can see and access everything within the doll it's placed in, as well as everything outside.</p>
<p>In programming terms:</p>
<ol>
<li><p><strong>Outer Scope</strong>: This is like the larger nesting doll. It contains variables and functions.</p>
</li>
<li><p><strong>Inner Scope</strong>: This is like the smaller nesting doll inside the larger one. It can access its own variables as well as those in the outer scope.</p>
</li>
</ol>
<h3 id="heading-examples"><strong>Examples</strong></h3>
<p>L<strong>exical Scope with Global Variable</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> globalVariable = <span class="hljs-string">'I am global'</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(globalVariable); <span class="hljs-comment">// Accessing globalVariable</span>
}
(); <span class="hljs-comment">// Output: "I am global"</span>
</code></pre>
<p>In this example, <code>globalVariable</code> is defined in the global scope. Any function defined within this scope has access to <code>globalVariable</code> directly.</p>
<p><strong>Example 2</strong></p>
<p>L<strong>exical Scope in Nested Functions</strong></p>
<pre><code class="lang-javascript"><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">let</span> outerVar = <span class="hljs-string">'Outer Variable'</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">middle</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">let</span> middleVar = <span class="hljs-string">'Middle Variable'</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-built_in">console</span>.log(outerVar + <span class="hljs-string">' '</span> + middleVar);
        }
        inner();
    }
    middle();
}
outer(); <span class="hljs-comment">// Output: "Outer Variable Middle Variable"</span>
<span class="hljs-built_in">console</span>.log(middleVar); <span class="hljs-comment">// Output: ReferenceError: middleVar is not defined</span>
</code></pre>
<p>Here, <code>inner</code> has access to both <code>outerVar</code> from its outer scope (<code>outer</code>) and <code>middleVar</code> from its immediate outer scope (<code>middle</code>) but cannot be accessed outside the <code>middle function</code>. This showcases how lexical scope works with nested functions.</p>
<p>So, <strong>lexical scope</strong> is all about where you place your variables in your code and how that affects where they can be accessed. It's a fundamental concept in understanding how JavaScript (and many other programming languages) handles variable visibility and accessibility.</p>
<h3 id="heading-what-does-it-mean-for-a-parent-function-to-have-finished-expecting">What does it mean for a parent function to have finished expecting?</h3>
<p>When a function finishes executing, its local variables and scope are typically destroyed or garbage collected. However, if there are inner functions (child functions) defined within the parent function, and those inner functions have been returned or are still in scope elsewhere in the program, they can maintain references to the variables in the parent function's scope. This is what creates a <strong>closure</strong>.</p>
<p>So when we say, "<strong>Closure</strong>, is a function that has access to the parent scope, even after the parent function has closed," <strong>What do we mean?</strong></p>
<p>This means that the inner function maintains a reference to the variables and parameters of the outer function's scope, allowing it to access and manipulate them even after the outer function has completed execution and its local variables should technically be out of scope.</p>
<p><strong>Example</strong></p>
<p>Consider the following scenario:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> outerVariable = <span class="hljs-string">'I am from the outer function'</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(outerVariable);
  }
  <span class="hljs-keyword">return</span> innerFunction;
}

<span class="hljs-keyword">const</span> innerFunc = outerFunction();
innerFunc(); <span class="hljs-comment">// Output: I am from the outer function</span>
</code></pre>
<p>In this example, <code>outerFunction</code> defines a variable <code>outerVariable</code> and also declares an inner function <code>innerFunction</code> that logs the value of <code>outerVariable</code>. <code>innerFunction</code> is then returned from <code>outerFunction</code>.</p>
<p>Now, when <code>outerFunction</code> is called and assigned to <code>innerFunc</code>, it actually returns <code>innerFunction</code>. But what's interesting is that even after <code>outerFunction</code> has finished executing and its execution context has been destroyed, <code>innerFunction</code> still retains access to the variables within its parent scope (i.e., the scope of <code>outerFunction</code>).</p>
<p>This behavior is what we refer to as closure. The inner function (<code>innerFunction</code>) has access to its parent function's scope (lexical scope), even after the parent function (<code>outerFunction</code>) has completed execution and been removed from the execution stack.</p>
<p><strong>To understand this better, let's break down the process:</strong></p>
<ol>
<li><p>When <code>outerFunction</code> is called, a new execution context is created with its own scope chain.</p>
</li>
<li><p>Inside <code>outerFunction</code>, <code>innerFunction</code> is defined, which creates a closure over the <code>outerVariable</code>.</p>
</li>
<li><p>When <code>innerFunction</code> is returned from <code>outerFunction</code> and assigned to <code>innerFunc</code>, it maintains a reference to its lexical environment, which includes the <code>outerVariable</code>.</p>
</li>
<li><p>Later, when <code>innerFunc</code> is invoked, it still has access to the <code>outerVariable</code> because of the closure created during its creation.</p>
</li>
</ol>
<h3 id="heading-why-do-you-need-to-understand-the-concept-of-closure">Why do you need to understand the concept of <strong>closure</strong>?</h3>
<p>Closure is important in JavaScript because it enables encapsulation, data privacy, and the management of asynchronous operations. With closures, you can create private variables and functions, control access to sensitive data, and maintain the integrity of your code. Closures are crucial for managing asynchronous operations, implementing callbacks, and event handling. They also allow for the dynamic generation of functions and provide a powerful tool for building modular and maintainable code. Understanding closures is essential for writing clean, efficient, and secure JavaScript applications.</p>
<p>Thank you ☺️ for taking the time to read. If you're interested in exploring similar topics further, I invite you to connect with me on LinkedIn and Twitter.</p>
<p><strong>LinkedIn</strong>: <a target="_blank" href="https://www.linkedin.com/in/garuba-abdul-azeez-713273167/">https://www.linkedin.com/in/garuba-abdul-azeez-713273167/</a></p>
<p><strong>Twitter</strong>: <a target="_blank" href="https://x.com/devAzeezjim?s=09">https://x.com/devAzeezjim?s=09</a></p>
<p>👋🏼👋🏼👋🏼</p>
]]></content:encoded></item></channel></rss>