<?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[ Lexical Scoping - 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[ Lexical Scoping - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 28 Jul 2026 20:13:14 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/lexical-scoping/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Lexical Scope in JavaScript – Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ In this article, we are going to understand what lexical scope is by going through some helpful examples.  We will also have a brief discussion about how JavaScript compiles and executes programs.  Lastly, we will have a look at how you can use lexic... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/lexical-scope-in-javascript/</link>
                <guid isPermaLink="false">66bb55524c9d249e52882f2d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Lexical Scoping ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Keyur Paralkar ]]>
                </dc:creator>
                <pubDate>Thu, 26 May 2022 15:27:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/spacex--p-KCm6xB9I-unsplash-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, we are going to understand what lexical scope is by going through some helpful examples. </p>
<p>We will also have a brief discussion about how JavaScript compiles and executes programs. </p>
<p>Lastly, we will have a look at how you can use lexical scope to explain undeclared variable errors or reference errors.</p>
<p>Without further ado, let's get started.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-does-javascript-execute-programs">How does JavaScript execute programs?</a></li>
<li><a class="post-section-overview" href="#heading-how-javascript-parsescompiles-and-executes-code">How JavaScript Parses/Compiles and Executes Code</a></li>
<li><a class="post-section-overview" href="#heading-syntax-error">Understanding Syntax Error</a></li>
<li><a class="post-section-overview" href="#heading-variablefunction-hoisting">Understanding Variable/Function Hoisting</a></li>
<li><a class="post-section-overview" href="#heading-what-is-lexical-scope">What is lexical scope</a>?</li>
<li><a class="post-section-overview" href="#heading-understanding-lexical-scope">Understanding Lexical Scope</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<h2 id="heading-how-does-javascript-execute-programs">How Does Javascript Execute Programs?</h2>
<p>Before understanding how JavaScript executes a code/program, we will first explore the different steps that are involved in any compilation process from a compiler theory perspective.</p>
<p>For any language, the compiler performs the following operations:</p>
<h3 id="heading-tokenizinglexing">Tokenizing/Lexing</h3>
<p>In this process, the entire program is divided into keywords which are called tokens. For example, consider the following statement: <code>let temp = 10</code> – once the tokenization is applied it will divide this statement into keywords as follows: <code>let</code>, <code>temp</code>, <code>=</code>, <code>10</code>. </p>
<p>Lexing and tokenizing terms are used interchangeably, but there is a subtle difference between them. Lexing is a process of tokenization but it also checks if it needs to be considered as a distinct token. We can consider <strong>Lexing</strong> to be a smart version of tokenization.</p>
<h3 id="heading-parsing">Parsing</h3>
<p>This is a process of collecting all the tokens generated in the previous step and turning them into a nested tree structure that grammatically represents the code.</p>
<p>This tree structure is called an abstract syntax tree (AST).</p>
<h3 id="heading-code-generation">Code Generation</h3>
<p>This process converts the AST into machine-readable code.</p>
<p>So this was a brief explanation of how the compiler works and generates a machine-readable code. </p>
<p>Of course there are more steps apart from the ones that are mentioned above. But explaining the other steps/phases of the compiler is out of scope for this article.</p>
<p>The most important observation that we can make about JS execution is that to execute code, it goes through two phases:</p>
<ol>
<li>Parsing</li>
<li>Execution</li>
</ol>
<p>Before we understand lexical scope, it is important to first understand how JavaScript executes a program. In the next sections, we will dive deeper into how these two phases work.</p>
<h2 id="heading-how-javascript-parsescompiles-and-executes-code">How JavaScript Parses/Compiles and Executes Code</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/Untitled.png" alt="Image" width="600" height="400" loading="lazy">
<em>Parsing phase</em></p>
<p>Let's first talk about the parsing phase. In this phase, the JavaScript engine goes through the entire program, assigns variables to their respective scopes, and also checks for any errors. If it finds an error then the execution of the program is stopped.</p>
<p>In the next phase, the actual execution of the code takes place.</p>
<p>To understand this in more detail we will look into the following two scenarios:</p>
<ul>
<li>Syntax Error</li>
<li>Variable hoisting</li>
</ul>
<h3 id="heading-syntax-error">Syntax Error</h3>
<p>To show you how JS first parses the program and then executes it, the best and simplest way is to demonstrate the behavior of a syntax error.</p>
<p>Consider the following buggy code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> token = <span class="hljs-string">"ABC"</span>;
<span class="hljs-built_in">console</span>.log(token);

<span class="hljs-comment">//Syntax error:</span>
<span class="hljs-keyword">const</span> newToken = %((token);
</code></pre>
<p>The above program will generate a syntax error at the last line. This is what the error will look like:</p>
<pre><code class="lang-javascript">Uncaught <span class="hljs-built_in">SyntaxError</span>: Unexpected token <span class="hljs-string">'%'</span>
</code></pre>
<p>If you look at the error, the JavaScript engines did not execute the <code>console.log</code> statement. Instead, it went through the entire program in the following manner:</p>
<ul>
<li>Line 1, found that there was a variable declaration and definition. So it stored the reference of the <code>token</code> variable in the current scope, that is global scope.</li>
<li>Line 2, JavaScript engine discovered that the <code>token</code> variable is being referenced. It first referred to the current scope to check if the <code>token</code> variable was present or not. If it’s present then it's referred to <code>token</code> variable’s declaration.</li>
<li>Line 3, the engine discovered that <code>newToken</code> variable was being declared and defined. It checked if any variable with the name <code>newToken</code> was present in the current scope or not. If yes, then throws a reference error. If no, then stores the reference of this variable in the current scope.</li>
<li>At the same line, the engine also discovered that it was trying to refer to a variable <code>%((token)</code>. But it found that it started with <code>%</code> and variable names cannot start with reserved keywords, so it threw a syntax error.</li>
</ul>
<h3 id="heading-variablefunction-hoisting">Variable/Function Hoisting</h3>
<p>Hoisting is a mechanism via which all the variables present in their respective scopes are hoisted, that is made available at the top. </p>
<p>Now let's take a look at the example below that will show you that hosting happens during the parsing phase and then execution happens:</p>
<pre><code class="lang-javascript">doSomething();

<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-built_in">console</span>.log(<span class="hljs-string">"How you doing?"</span>);
}
</code></pre>
<p>In the above program, the engine goes through the program in the following manner:</p>
<ul>
<li>Line 1, JavaScript engine encountered a function called <code>doSomething</code>. It searched to see if <code>doSomething</code> was available in the current scope. If yes then it refers to the function or else it throws a reference error.</li>
<li>It turned out that during the parsing phase, the engine found the <code>function doSomething</code> line to be present in the current scope. Therefore, it added this variable’s reference in the current scope and made it available throughout the entire program.</li>
<li>Finally, the <code>doSomething</code> function printed out the string <code>How you doing?</code>.</li>
</ul>
<p>As we can see from the above explanation, the code was first parsed so as to generate some intermediary code that makes sure the variable/function (that is <code>doSomething</code>) referenced in the current scope is made available. </p>
<p>In the next phase, JavaScript knows about the function and so starts to execute.</p>
<p>From the above examples, we can safely conclude that the JavaScript engine does the following things before executing the code:</p>
<ol>
<li>Parses the code.</li>
<li>Generates the intermediary code that gives a description of the variables/functions that are available.</li>
<li>Using the above intermediary code, it then starts the execution of the program.</li>
</ol>
<h2 id="heading-what-is-lexical-scope">What is Lexical Scope?</h2>
<p>The process of determining the scopes of the variables/functions during runtime is called lexical scoping. The word <em>lexical</em> comes from the <em>lexical/tokenization phase</em> of the JS compiler steps.</p>
<p>During runtime, JavaScript does these two things: <code>parsing</code> and <code>execution</code>. As you learned in the last section, during the parsing phase the scopes of the variables/functions are defined. That is why it was important to first understand the parsing phase of the code execution since it lays down the foundation for understanding lexical scope.</p>
<p>In laymen's terms, the parsing phase of the JavaScript engine is where lexical scoping takes place.</p>
<p>Now that we know the basics of it, let's go through some of the main characteristics of lexical scope:</p>
<p>First of all, during the parsing phase, a scope is assigned/referenced to a variable where it is declared. </p>
<p>For example, consider a scenario where a variable is referenced in the inner function and its declaration is present in the global scope. In this case the inner variable is assigned with the outer scope, that is the global scope.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/ezgif.com-gif-maker--1---1-.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Scope assigned illustration</em></p>
<p>Then, while assigning scope to a variable, the JavaScript engine checks its parent scopes for the availability of the variable. </p>
<p>If the variable is present then that parent scope is applied to the variable. If a variable is not found in any of the parent scopes then a reference error is thrown.  </p>
<p>Take a look at the below illustration that demonstrates how a variable’s scope is searched.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/ezgif.com-gif-maker--3---1-.gif" alt="Image" width="600" height="400" loading="lazy">
<em>JS engine successfully finding a variable by going through each scope</em></p>
<p>Here is an illustration that represents the JS engine trying to find a variable that does not exists in any scope:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/ezgif.com-gif-maker--6---1-.gif" alt="Image" width="600" height="400" loading="lazy">
<em>JS engine throwing reference error</em></p>
<h2 id="heading-understanding-lexical-scope">Understanding Lexical Scope</h2>
<p>In the above section, we defined what lexical scope is. We also understood what characteristics it has. </p>
<p>In this section, we are going to understand lexical scope with the help of an example. As they say, it's always easier to understand difficult topics by looking at examples from real-life, day-to-day code. Let’s get started.</p>
<p>The example that we are going to use involves coloring areas of our code that have similar scopes. This may sound confusing, but let me demonstrate this with a simple illustration.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/Global-and-Functional-Scope--1---1-.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Understanding lexical scope with a coloring example</em></p>
<p>Let's take a step back and understand what is going on in this illustration.</p>
<p>We have the following things in our program:</p>
<ul>
<li><code>empData</code>: Array of objects.</li>
<li><code>allPositions</code>: Array of strings that consists of all the employee positions.</li>
<li>Lastly, we have a console statement that prints out <code>allPositions</code> variables.</li>
</ul>
<p>Now let's take a look at what happens in the parsing phase of this program:</p>
<ul>
<li>The engine starts with the first line, and it encounters a variable declaration <code>empData</code>.</li>
<li>The engine then checks if the <code>empData</code> is available in the current scope or not. Since there is no similar variable found, it checks the existence of this variable in its parent scope.</li>
<li>The engine will stop its search over here since there is no scope available and also the current scope is the global scope.</li>
<li>Next, the engine assigns an <code>undefined</code> value to the <code>empData</code> during the parsing phase so that once any nested scope tries to reference this variable, then it can be used.</li>
<li>The right-hand side of this assignment operator is evaluated during the execution phase of the program.</li>
<li>In a similar manner, the engine does the same for the <code>allPositions</code> variable and assigns it an <code>undefined</code> value.</li>
<li>But on the right-hand side, we are also referencing the <code>empData</code> variable. At this stage, the engine checks if this variable is available in the current scope. Since it is available, it refers to the same (that is, present in the global scope).</li>
<li>The engine is still on the right-hand side since it found out that there is an arrow function inside of the map function. Since the engine has encountered the function definition, it creates a new scope. In the gif, this is number 2.</li>
<li>Since this is a new scope, we are going to color code it black.</li>
<li>This arrow function has an argument of <code>data</code> and returns <code>data.position</code>. In the parsing phase, the engine hoists all the variables that are required by referencing the variables present in the current scope as well as in its parent scope. </li>
<li>Inside this function, the <code>data</code> variable is referenced so the engine checks if the current scope has this variable. Since the variable is present in the current scope, it refers to the same.</li>
<li>Once the engine encounters the <code>}</code> brace, it moves out of the functional scope.</li>
<li>Finally, at the end of the program, we have a console statement that displays <code>allPositions</code> variables. Since it is referencing the <code>allPositions</code> variable, it searches in the current scope (that is global scope). Since it is found, it refers to the same in the <code>console</code> statement.</li>
</ul>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we learned about what lexical scope means, and learned how it works by looking at a simple coloring example.</p>
<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[ Lexical Scope in JavaScript – What Exactly Is Scope in JS? ]]>
                </title>
                <description>
                    <![CDATA[ The term “lexical scope” may seem tricky to grasp at first glance. But it's helpful to understand what each word means. So this article will explain lexical scope by first examining the meaning of “lexical” and “scope”. So, let’s get it started by un... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-lexical-scope-tutorial/</link>
                <guid isPermaLink="false">66ba0dfaa1a94b68c6ae948f</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Lexical Scoping ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Thu, 19 Aug 2021 19:56:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/kristina-tripkovic-EGmwwDzme6s-unsplash-javascript-lexical-scope-codesweetly.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The term “<strong>lexical scope</strong>” may seem tricky to grasp at first glance. But it's helpful to understand what each word means.</p>
<p>So this article will explain lexical scope by first examining the meaning of “lexical” and “scope”.</p>
<p>So, let’s get it started by understanding the term “scope”.</p>
<h2 id="heading-what-exactly-is-scope">What exactly is Scope?</h2>
<p><strong>Scope</strong> refers to the <em>area</em> where an item (such as a function or variable) is visible and accessible to other <a target="_blank" href="https://www.codesweetly.com/document-vs-data-vs-code/">code</a>.</p>
<p><strong>Note:</strong></p>
<ul>
<li><strong>Scope</strong> means area, space, or region.</li>
<li><strong>Global scope</strong> means global space or a public space.</li>
<li><strong>Local scope</strong> means a local region or a restricted region.</li>
</ul>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a variable in the global scope:</span>
<span class="hljs-keyword">const</span> fullName = <span class="hljs-string">"Oluwatobi Sofela"</span>;

<span class="hljs-comment">// Define nested functions:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">profile</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayName</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">writeName</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> fullName;
    }
    <span class="hljs-keyword">return</span> writeName();
  }
  <span class="hljs-keyword">return</span> sayName();
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-fqqxjl?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we defined the <code>fullName</code> variable in the global scope. This means that it is visible and accessible globally to all code within the script.</p>
<p>But we defined <code>writeName()</code> within the <code>sayName()</code> function, so it is locally scoped to <code>sayName()</code>.</p>
<p>In other words, <code>writeName()</code> is locally visible and accessible only to code in the <code>sayName()</code> function.</p>
<p>Keep in mind that whenever the <code>writeName()</code> function gets invoked, the computer will <em>not</em> go straight to the global scope to call the <code>fullName</code> variable. Instead, it must sequentially go through the <a class="post-section-overview" href="#heading-what-is-a-scope-chain">scope chain</a> to look for <code>fullName</code>.</p>
<h2 id="heading-what-is-a-scope-chain">What is a Scope Chain?</h2>
<p>A <strong>scope chain</strong> refers to the <em>unique</em> spaces that exist from the scope where a variable got <em>called</em> to the global scope.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a variable in the global scope:</span>
<span class="hljs-keyword">const</span> fullName = <span class="hljs-string">"Oluwatobi Sofela"</span>;

<span class="hljs-comment">// Define nested functions:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">profile</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayName</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">writeName</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> fullName;
    }
    <span class="hljs-keyword">return</span> writeName();
  }
  <span class="hljs-keyword">return</span> sayName();
}
</code></pre>
<p>In the snippet above, observe that the <code>fullName</code> variable got called from the <code>writeName()</code> function's scope.</p>
<p>Therefore, the scope chain that exists from the variable’s call to the global scope is:</p>
<p><strong>writeName() scope ---&gt; sayName() scope ---&gt; profile() scope ---&gt; global scope</strong></p>
<p>In other words, there are four (4) spaces from <code>fullName</code>’s invocation scope to its lexical scope (the <em>global scope</em> in this instance).</p>
<p><strong>Note:</strong> The global scope is the last link in <a target="_blank" href="https://www.codesweetly.com/html-css-javascript/">JavaScript</a>'s scope chain.</p>
<h2 id="heading-how-does-the-scope-chain-work">How Does the Scope Chain Work?</h2>
<p>JavaScript's scope chain determines the hierarchy of places the computer must go through — one after the other — to find the lexical scope (origin) of the specific variable that got called.</p>
<p>For instance, consider the code below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a variable in the global scope:</span>
<span class="hljs-keyword">const</span> fullName = <span class="hljs-string">"Oluwatobi Sofela"</span>;

<span class="hljs-comment">// Define nested functions:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">profile</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayName</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">writeName</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> fullName;
    }
    <span class="hljs-keyword">return</span> writeName();
  }
  <span class="hljs-keyword">return</span> sayName();
}
</code></pre>
<p>In the snippet above, whenever the <code>profile()</code> function gets invoked, the computer will first invoke the <code>sayName()</code> function (which is the only code in the <code>profile()</code> function).</p>
<p>Secondly, the computer will invoke the <code>writeName()</code> function (which is the only code in the <code>sayName()</code> function).</p>
<p>At this point, since the code in <code>writeName()</code> instructs the computer to call and return the <code>fullName</code> variable's content, the computer will call <code>fullName</code>. But it will not go directly to the global scope to call <code>fullName</code>.</p>
<p>Instead, the computer must go <em>step-by-step</em> through the <em>scope chain</em> to look for the <em>lexical scope</em> of <code>fullName</code>.</p>
<p>So, here are the sequential steps the computer must take to locate <code>fullName</code>'s lexical scope:</p>
<ol>
<li>Firstly, the computer will check if <code>fullName</code> got defined locally within the <code>writeName()</code> function. But it will find no <code>fullName</code> definition there, so it moves up to the next scope to continue its quest.</li>
<li>Secondly, the computer will search for <code>fullName</code>'s definition in <code>sayName()</code> (the next space in the scope chain). Still, it doesn't find it there, so it climbs up the ladder to the next scope.</li>
<li>Thirdly, the computer will search for <code>fullName</code>'s definition in the <code>profile()</code> function. Yet still, <code>fullName</code> is not found there. So the computer goes forward to seek <code>fullName</code>'s lexical scope in the next region of the scope chain.</li>
<li>Fourthly, the computer goes to the <em>global scope</em> (the following scope after <code>profile()</code>). Fortunately, it finds fullName's definition there! Therefore, it gets its content (<code>"Oluwatobi Sofela"</code>) and returns it.</li>
</ol>
<h2 id="heading-time-to-practice-with-scope">Time to Practice with Scope 🤸‍♂️🏋️‍♀️🏊‍♀️</h2>
<p>Consider the script below. Which of the three <code>fullName</code> variables will the computer call?</p>
<pre><code class="lang-js"><span class="hljs-comment">// First fullName variable defined in the global scope:</span>
<span class="hljs-keyword">const</span> fullName = <span class="hljs-string">"Oluwatobi Sofela"</span>;

<span class="hljs-comment">// Nested functions containing two more fullName variables:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">profile</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">"Tobi Sho"</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayName</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">"Oluwa Sofe"</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">writeName</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> fullName;
    }
    <span class="hljs-keyword">return</span> writeName();
  }
  <span class="hljs-keyword">return</span> sayName();
}
</code></pre>
<p>Will the computer call the first, second, or third <code>fullName</code> variable?</p>
<p><strong>Note:</strong> You will benefit much more from this tutorial if you attempt the exercise yourself.</p>
<p>If you get stuck, don’t be discouraged. Instead, review the lesson and give it another try.</p>
<p>Once you’ve given it your best shot (you’ll only cheat yourself if you don’t!), go ahead to see the correct answer below.</p>
<h2 id="heading-did-you-get-it-right">Did you get it right?</h2>
<p>Out of the three <code>fullName</code> <em>definitions</em> present in the script above, the computer will call and return the one defined in the <code>sayName()</code> function.</p>
<p><code>sayName()</code>’s <code>fullName</code> variable will get called because <code>sayName()</code> is the scope inside which the computer will first find a <code>fullName</code> definition.</p>
<p>Therefore, when <code>profile()</code> gets invoked, the returned value will be <code>"Oluwa Sofe"</code>.</p>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-9mpvfv?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p><strong>Some things to keep in mind:</strong></p>
<ul>
<li>Suppose the computer did not find <code>fullName</code>'s definition in any of the scopes. In such a case, the computer will return <code>Uncaught ReferenceError: fullName is not defined</code>.</li>
<li>The global scope is always the last scope of any JavaScript scope chain. In other words, the global scope is where all searches will end.</li>
<li>An inner (child) scope has access to its parent (outer) scope, but an outer scope does not have access to its child scope.<br>For instance, in the snippet above, <code>writeName()</code> can access codes inside any of its parent scope (<code>sayName()</code>, <code>profile()</code>, or the <em>global scope</em>).<br>However, neither <code>sayName()</code>, <code>profile()</code>, nor the <em>global scope</em> can access any of <code>writeName()</code>'s codes.</li>
</ul>
<h2 id="heading-quick-review-of-scope-so-far">Quick Review of Scope So Far</h2>
<p>JavaScript scope is all about space.</p>
<p>So next time your partner calls you to their private scope, remember they are inviting you to their private space 😜!</p>
<p>When you get there, be sure to ask them about their best lexical game...</p>
<p>But what does lexical mean, I hear you ask? Let’s find out below.</p>
<h2 id="heading-what-does-lexical-mean">What Does Lexical Mean?</h2>
<p><strong>Lexical</strong> refers to the definition of things.</p>
<p>Anything related to creating words, expressions, or variables is termed <em>lexical</em>.</p>
<p>For instance, a <a target="_blank" href="https://en.wikipedia.org/wiki/Scrabble">scrabble</a> game is a lexical activity because it relates to the creation of words.</p>
<p>Also, someone whose job relates to linguistics (the study of languages) has a lexical career.</p>
<p><strong>Note:</strong> Another name for a dictionary is a <em>lexicon</em>. In other words, a lexicon is a dictionary where words are listed and defined.</p>
<p>So now that we know what scope and lexical mean, we can talk about lexical scope.</p>
<h2 id="heading-what-is-lexical-scope-in-javascript">What is Lexical Scope in JavaScript?</h2>
<p><strong>Lexical scope</strong> is the <em>definition</em> area of an expression.</p>
<p>In other words, an item's lexical scope is the place in which the item got <em>created</em>.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Another name for lexical scope is <em>static scope</em>.</li>
<li>The place an item got invoked (or called) is not necessarily the item's lexical scope. Instead, an item's <em>definition space</em> is its lexical scope.</li>
</ul>
<h3 id="heading-example-of-lexical-scope">Example of Lexical Scope</h3>
<p>Consider the code below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a variable in the global scope:</span>
<span class="hljs-keyword">const</span> myName = <span class="hljs-string">"Oluwatobi"</span>;

<span class="hljs-comment">// Call myName variable from a function:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> myName;
}
</code></pre>
<p>In the snippet above, notice that we <em>defined</em> the <code>myName</code> variable in the global scope and <em>called</em> it in the <code>getName()</code> function.</p>
<p><strong>Question:</strong> Which of the two spaces is <code>myName</code>’s lexical scope? Is it the <em>global scope</em> or the <code>getName()</code> function’s local scope?</p>
<p><strong>Answer:</strong> Remember that <em>lexical scope</em> means <em>definition space</em> — not <em>invocation space</em>. Therefore, <code>myName</code>’s lexical scope is the <em>global scope</em> because we defined <code>myName</code> in the global environment.</p>
<h3 id="heading-another-example-of-lexical-scope">Another example of lexical scope</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> myName = <span class="hljs-string">"Oluwatobi"</span>;
  <span class="hljs-keyword">return</span> myName;
}
</code></pre>
<p><strong>Question:</strong> Where is <code>myName</code>’s lexical scope?</p>
<p><strong>Answer:</strong> Notice that we created and called <code>myName</code> within <code>getName()</code>. Therefore, <code>myName</code>’s lexical scope is <code>getName()</code>’s local environment because <code>getName()</code> is <code>myName</code>’s definition space.</p>
<h2 id="heading-how-does-lexical-scope-work">How Does Lexical Scope Work?</h2>
<p>A JavaScript expression’s definition environment determines the <a target="_blank" href="https://www.codesweetly.com/document-vs-data-vs-code/">code</a> permitted to access it.</p>
<p>In other words, only code within an item's lexical scope can access it.</p>
<p>For instance, consider the code below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showLastName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> lastName = <span class="hljs-string">"Sofela"</span>;
  <span class="hljs-keyword">return</span> lastName;
}

<span class="hljs-comment">// Define another function:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayFullName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">"Oluwatobi "</span> + lastName;
  <span class="hljs-keyword">return</span> fullName;
}

<span class="hljs-comment">// Invoke displayFullName():</span>
<span class="hljs-built_in">console</span>.log(displayFullName());

<span class="hljs-comment">// The invocation above will return:</span>
Uncaught <span class="hljs-built_in">ReferenceError</span>: lastName is not defined
</code></pre>
<p>Notice that the invocation of <code>displayFullName()</code> in the snippet above returned an <code>Uncaught ReferenceError</code>. The error returned because only code within an item's lexical scope can access the item.</p>
<p>Therefore, neither the <code>displayFullName()</code> function nor its internal code can access the <code>lastName</code> variable because <code>lastName</code> got defined in a different scope.</p>
<p>In other words, <code>lastName</code>’s lexical scope is different from that of <code>displayFullName()</code>.</p>
<p><code>lastName</code>’s definition space is <code>showLastName()</code> while <code>displayFullName()</code>’s lexical scope is the global environment.</p>
<p>Now, consider this other code below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showLastName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> lastName = <span class="hljs-string">"Sofela"</span>;
  <span class="hljs-keyword">return</span> lastName;
}

<span class="hljs-comment">// Define another function:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayFullName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">"Oluwatobi "</span> + showLastName();
  <span class="hljs-keyword">return</span> fullName;
}

<span class="hljs-comment">// Invoke displayFullName():</span>
<span class="hljs-built_in">console</span>.log(displayFullName());

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi Sofela"</span>
</code></pre>
<p>In the snippet above, <code>displayFullName()</code> successfully returned <code>"Oluwatobi Sofela"</code> because <code>displayFullName()</code> and <code>showLastName()</code> are in the same lexical scope.</p>
<p>In other words, <code>displayFullName()</code> could invoke <code>showLastName()</code> because the two functions are both defined in the global scope.</p>
<p><strong>Note:</strong></p>
<ul>
<li>In example 2 above, <code>displayFullName()</code> did not gain access to <code>showLastName()</code>'s <code>lastName</code> variable.<br>Instead, <code>displayFullName()</code> invoked <code>showLastName()</code> — which then returned the content of its <code>lastName</code> variable.</li>
<li>An alternative to the lexical scope is the <a target="_blank" href="https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scope_vs._dynamic_scope_2">dynamic scope</a> — but it rarely gets used in programming. Only a few languages, like bash, use dynamic scope.</li>
</ul>
<h2 id="heading-wrapping-it-up">Wrapping it up</h2>
<p>Any time you hear lexical, think definition.</p>
<p>So, the lexical scope of a car, variable, phone, function, or swimsuit refers to its definition region.</p>
<h2 id="heading-overview">Overview</h2>
<p>This article discussed what lexical scope means in <a target="_blank" href="https://www.codesweetly.com/html-css-javascript/">JavaScript</a>. We also looked at why it is an important programming concept.</p>
<p>Thanks for reading!</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[ 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>
        
    </channel>
</rss>
