<?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[ Scope - 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[ Scope - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 25 Jun 2026 10:02:36 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/scope/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Scope in JavaScript – Global vs Local vs Block Scope Explained ]]>
                </title>
                <description>
                    <![CDATA[ In the vast world of programming, scope is a fundamental concept. It underpins the behavior of variables in any given programming language. In the context of JavaScript, a language renowned for its widespread use in web development, understanding sco... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/scope-in-javascript-global-vs-local-vs-block-scope/</link>
                <guid isPermaLink="false">66d45d602472e5ed2fa07b9d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Scope ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Adekola Olawale ]]>
                </dc:creator>
                <pubDate>Mon, 13 Nov 2023 17:40:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/Scope-in-JavaScript.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the vast world of programming, scope is a fundamental concept. It underpins the behavior of variables in any given programming language.</p>
<p>In the context of JavaScript, a language renowned for its widespread use in web development, understanding scope is crucial to writing efficient and bug-free code.</p>
<p>Whether you're a seasoned developer or just starting your coding journey, the concept of scope in JavaScript is a topic that demands your attention.</p>
<h2 id="heading-what-is-scope">What is Scope?</h2>
<p>At its core, scope in JavaScript refers to the context or environment in which variables are declared and can be accessed.</p>
<p>It dictates the visibility and lifetime of a variable, determining where in your code a particular variable is valid and accessible.</p>
<p>A solid grasp of scope is indispensable because it can affect how your code behaves and interacts with other parts of your application.</p>
<p>Scope is not a mere technicality – it profoundly influences the way you structure your code, manage your data, and prevent conflicts between variables.</p>
<p>A lack of understanding of scope can lead to bugs, unexpected behaviors, and increased maintenance efforts, all of which can be avoided with proper comprehension and application of scope rules.</p>
<p>JavaScript offers various types of scope, with the three primary ones being global, local, and block scope.</p>
<p>These scopes control the accessibility of variables in different parts of your code and play a pivotal role in maintaining code organization and preventing variable conflicts.</p>
<p>The purpose of this article is to provide a comprehensive understanding of the different scopes in JavaScript, namely global, local, and block scope.</p>
<p>We will delve into the intricacies of each type of scope, explore examples to illustrate their practical applications, and highlight best practices for utilizing them effectively.</p>
<p>By the end of this article, you will have a solid foundation in JavaScript scope, enabling you to write more robust, maintainable, and efficient code in your web development projects.</p>
<p>So, let's embark on this journey to unravel the mysteries of scope in JavaScript.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-global-scope">Global Scope</a></li>
</ul>
<ul>
<li><p><a class="post-section-overview" href="#heading-variables-declared-in-global-scope">Variables Declared in Global Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-access-global-variables">How to Access Global Variables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-potential-issues-with-global-scope">Potential Issues with Global Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-for-using-global-scope">Best Practices for Using Global Scope</a></p>
</li>
</ul>
<ul>
<li><a class="post-section-overview" href="#heading-local-scope">Local Scope</a></li>
</ul>
<ul>
<li><p><a class="post-section-overview" href="#heading-variables-declared-in-local-scope">Variables Declared in Local Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-access-local-variables">How to Access Local Variables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-concept-of-variable-shadowing">The Concept of Variable Shadowing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-benefits-of-using-local-scope">Benefits of Using Local Scope</a></p>
</li>
</ul>
<ul>
<li><a class="post-section-overview" href="#heading-block-scope">Block Scope</a></li>
</ul>
<ul>
<li><p><a class="post-section-overview" href="#heading-variables-declared-in-block-scope">Variables Declared in Block Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-differences-between-block-scope-and-local-scope">Differences between Block Scope and Local Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-block-scope-with-let-and-const">How to Use Block Scope with <code>let</code> and <code>const</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-block-scope-in-conditional-statements-and-loops">Block Scope in Conditional Statements and Loops</a></p>
</li>
</ul>
<ul>
<li><a class="post-section-overview" href="#heading-scope-chain">Scope Chain</a></li>
</ul>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-javascript-resolves-variable-references">How JavaScript Resolves Variable References</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-lexical-scope">Understanding Lexical Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-nested-scopes-and-their-impact-on-the-scope-chain">Nested Scopes and Their Impact on the Scope Chain</a></p>
</li>
</ul>
<ul>
<li><a class="post-section-overview" href="#heading-closures-and-function-scope">Closures and Function Scope</a></li>
</ul>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-function-scope-and-closures-are-related">How Function Scope and Closures are Related</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practical-examples-of-closures">Practical Examples of Closures</a></p>
</li>
</ul>
<ul>
<li><a class="post-section-overview" href="#heading-scope-best-practices">Scope Best Practices</a></li>
</ul>
<ul>
<li><p><a class="post-section-overview" href="#heading-tips-for-avoiding-common-scope-related-issues">Tips for Avoiding Common Scope-Related Issues</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-importance-of-minimizing-global-variables">The Importance of Minimizing Global Variables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-appropriate-variable-names-for-clarity">Using Appropriate Variable Names for Clarity</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-different-types-of-scope">When to Use Different Types of Scope</a></p>
</li>
</ul>
<ul>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-global-scope">Global Scope</h2>
<p>In JavaScript, global scope is the widest scope available. Variables declared in global scope are accessible from anywhere in your code, whether it's inside functions, conditional statements, loops, or other blocks of code.</p>
<p>You can think of global scope as the "public square" of your program, where everyone can see and access what's going on.</p>
<p>To illustrate, let's consider an analogy. Imagine your JavaScript program as a small town, and the global scope as the town's central square.</p>
<p>Everything you declare in global scope is like putting up a billboard in the square for everyone to see. Any function or code block within your program can read and modify these global variables.</p>
<h3 id="heading-variables-declared-in-global-scope">Variables Declared in Global Scope</h3>
<p>Variables declared in global scope are typically defined outside of any functions or code blocks. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> globalVariable = <span class="hljs-string">"I'm in global scope"</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-comment">// This function can access globalVariable</span>
  <span class="hljs-built_in">console</span>.log(globalVariable);
}

myFunction();
</code></pre>
<p>Here, <code>globalVariable</code> is declared in global scope, and <code>myFunction</code> can access and use it directly.</p>
<h3 id="heading-how-to-access-global-variables">How to Access Global Variables</h3>
<p>Accessing global variables is straightforward. You can use them within functions or any part of your code without any special effort. It's like having a public notice board in the town square where everyone can read and post messages.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> townMessage = <span class="hljs-string">"Welcome to our lovely town!"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">welcomeMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(townMessage); <span class="hljs-comment">// Accessing the global variable</span>
}

welcomeMessage();
</code></pre>
<h3 id="heading-potential-issues-with-global-scope">Potential Issues with Global Scope</h3>
<p>While global scope can be quite convenient, it comes with potential downsides.</p>
<p>Since global variables are accessible from anywhere, they are susceptible to unintended changes and conflicts.</p>
<p>For instance, if multiple parts of your code modify the same global variable, it can lead to unexpected behaviors and bugs that are hard to track down.</p>
<p>Moreover, global variables can make your code less modular and organized. If everything is in the town square, it becomes challenging to manage and isolate different aspects of your program.</p>
<h3 id="heading-best-practices-for-using-global-scope">Best Practices for Using Global Scope</h3>
<p>To minimize the potential issues associated with global scope, consider the following best practices:</p>
<ol>
<li><p><strong>Use global scope sparingly</strong>: Only declare variables in global scope when they genuinely need to be accessed globally.</p>
</li>
<li><p><strong>Avoid overwriting global variables</strong>: Be cautious when modifying global variables to prevent unintended side effects.</p>
</li>
<li><p><strong>Use descriptive variable names</strong>: Choose variable names that clearly convey their purpose, especially in global scope where they can affect many parts of your code.</p>
</li>
</ol>
<p>Global scope in JavaScript is like the town square where everyone can access and modify variables.</p>
<p>While it provides broad visibility, it should be used judiciously to maintain code clarity and prevent unintended side effects.</p>
<p>Understanding global scope is a crucial step in mastering JavaScript's scope mechanics.</p>
<h2 id="heading-local-scope">Local Scope</h2>
<p>Local scope in JavaScript is like a private room within a building – it's an enclosed space where variables are only accessible from within that specific room.</p>
<p>When you declare a variable in local scope, it is limited in visibility to the block of code, function, or conditional statement in which it is defined.</p>
<p>Variables in local scope are protected from interference or modification by code outside their scope, providing a level of isolation.</p>
<h3 id="heading-variables-declared-in-local-scope">Variables Declared in Local Scope</h3>
<p>Variables in local scope are typically declared within functions, conditional statements, loops, or other code blocks.</p>
<p>These variables are, in essence, "local" to that block of code, and they cannot be directly accessed from outside it.</p>
<p>Consider this analogy: if a local scope is like a private room, a variable declared within that scope is akin to an object or piece of furniture placed inside that room.</p>
<p>Others can't directly interact with it from outside – they would need permission, like a key, to enter the room and access the variable.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><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-keyword">var</span> localVariable = <span class="hljs-string">"I'm in local scope"</span>;
  <span class="hljs-built_in">console</span>.log(localVariable);
}

myFunction();
<span class="hljs-comment">// Accessing localVariable here would result in an error</span>
</code></pre>
<p>In this code, <code>localVariable</code> is in local scope, which means it's only accessible within the <code>myFunction</code> block.</p>
<h3 id="heading-how-to-access-local-variables">How to Access Local Variables</h3>
<p>Accessing local variables is straightforward within the scope where they are defined.</p>
<p>These variables are isolated from the outside world, ensuring that they won't accidentally clash with other variables in your program</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> greeting = <span class="hljs-string">"Hello, world!"</span>;
  <span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// Accessing the local variable</span>
}

greet();
</code></pre>
<p>In this example, <code>greeting</code> is a local variable, and it's safely accessed within the <code>greet</code> function without affecting variables outside of it.</p>
<h3 id="heading-the-concept-of-variable-shadowing">The Concept of Variable Shadowing</h3>
<p>Variable shadowing occurs when you declare a variable with the same name inside a local scope, effectively "hiding" the variable with the same name in a higher scope.</p>
<p>This is similar to placing an object with the same name in multiple rooms, and the one in the inner room takes precedence when you try to access it.</p>
<p>Consider this example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> message = <span class="hljs-string">"Global message"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> message = <span class="hljs-string">"Local message"</span>; <span class="hljs-comment">// This "shadows" the global variable</span>
  <span class="hljs-built_in">console</span>.log(message); <span class="hljs-comment">// Accessing the local variable</span>
}

showMessage();
<span class="hljs-built_in">console</span>.log(message); <span class="hljs-comment">// Accessing the global variable</span>
</code></pre>
<p>In this code, the local variable <code>message</code> shadows the global variable with the same name when you're inside the <code>showMessage</code> function.</p>
<h3 id="heading-benefits-of-using-local-scope">Benefits of Using Local Scope</h3>
<p>Local scope offers several advantages:</p>
<ol>
<li><p><strong>Isolation</strong>: It prevents unintended interference with variables in other parts of your code, reducing the risk of bugs and conflicts.</p>
</li>
<li><p><strong>Modularity</strong>: It allows you to compartmentalize your code, making it more manageable and easier to maintain.</p>
</li>
<li><p><strong>Reusability</strong>: Variables in local scope can be defined and used within specific functions or blocks, promoting code reusability without affecting the rest of your program.</p>
</li>
</ol>
<p>Understanding local scope and how it provides encapsulation is a fundamental concept in JavaScript that allows for organized, modular, and less error-prone code.</p>
<h2 id="heading-block-scope">Block Scope</h2>
<p>Block scope in JavaScript is like a series of nested boxes within a larger container, each with its own set of variables.</p>
<p>Unlike global and local scopes, which are defined by functions or global context, block scope is created within specific code blocks, such as conditional statements (if, else, switch) and loops (for, while).</p>
<p>Variables declared in block scope are confined to that block, offering a high degree of isolation.</p>
<p>To illustrate, imagine a Russian nesting doll. The larger doll represents the global scope, and each smaller doll nested inside it represents a block scope.</p>
<p>Variables within a block scope can't escape to the outer scopes, just as a doll within a doll can't get out.</p>
<h3 id="heading-variables-declared-in-block-scope">Variables Declared in Block Scope</h3>
<p>Variables declared in block scope are only accessible within the block in which they are defined. These variables are like hidden treasures inside each nesting doll, known and accessible only within their respective compartments.</p>
<p>Here's an example using a block scope within an <code>if</code> statement:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
  <span class="hljs-keyword">let</span> blockVariable = <span class="hljs-string">"I'm in block scope"</span>;
  <span class="hljs-built_in">console</span>.log(blockVariable);
}
<span class="hljs-comment">// Accessing blockVariable here would result in an error</span>
</code></pre>
<p>In this code, <code>blockVariable</code> is defined within the block created by the <code>if</code> statement and is inaccessible outside of it.</p>
<h3 id="heading-differences-between-block-scope-and-local-scope">Differences between Block Scope and Local Scope</h3>
<p>Block scope is often confused with local scope, but there's a key distinction.</p>
<p>In local scope, variables are typically defined within a function, while block scope is created within code blocks like <code>if</code>, <code>for</code>, or <code>while</code> statements.</p>
<p>Local scope is function-level, meaning it encompasses the entire function, while block scope is limited to the specific block where the variable is declared.</p>
<p>Consider the following code to highlight the difference:</p>
<pre><code class="lang-javascript"><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-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">var</span> localVariable = <span class="hljs-string">"I'm in block scope"</span>;
    <span class="hljs-keyword">let</span> blockVariable = <span class="hljs-string">"I'm also in block scope"</span>;
  }
  <span class="hljs-built_in">console</span>.log(localVariable); <span class="hljs-comment">// Accessible</span>
  <span class="hljs-built_in">console</span>.log(blockVariable); <span class="hljs-comment">// Error: blockVariable is not defined</span>
}
</code></pre>
<p>In this example, <code>localVariable</code> is accessible within the function because it's in local scope. On the other hand, <code>blockVariable</code> is accessible only within the <code>if</code> block due to block scope.</p>
<h3 id="heading-how-to-use-block-scope-with-let-and-const">How to Use Block Scope with <code>let</code> and <code>const</code></h3>
<p>The introduction of the <code>let</code> and <code>const</code> keywords in JavaScript significantly enhanced block scope.</p>
<p>These keywords allow you to declare variables with block scope, making it easier to control variable visibility and lifespan.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">exampleBlockScope</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">let</span> blockVariable = <span class="hljs-string">"I'm block-scoped with 'let'"</span>;
    <span class="hljs-keyword">const</span> constantBlockVar = <span class="hljs-string">"I'm block-scoped with 'const'"</span>;
  }
  <span class="hljs-built_in">console</span>.log(blockVariable); <span class="hljs-comment">// Error: blockVariable is not defined</span>
  <span class="hljs-built_in">console</span>.log(constantBlockVar); <span class="hljs-comment">// Error: constantBlockVar is not defined</span>
}
</code></pre>
<p>In this code, <code>blockVariable</code> and <code>constantBlockVar</code> are block-scoped and inaccessible outside their respective blocks.</p>
<h3 id="heading-block-scope-in-conditional-statements-and-loops">Block Scope in Conditional Statements and Loops</h3>
<p>Block scope is often used in conditional statements and loops to control the scope of variables. Consider this example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkCondition</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> result = <span class="hljs-string">"Before condition"</span>;
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">let</span> result = <span class="hljs-string">"Inside condition"</span>; <span class="hljs-comment">// Block-scoped variable</span>
  }
  <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// "Before condition" from the outer scope</span>
}
</code></pre>
<p>In this code, the variable <code>result</code> is block-scoped inside the <code>if</code> statement, and it doesn't affect the <code>result</code> variable in the outer scope.</p>
<p>Block scope is a powerful tool for managing variable visibility and preventing unintended variable clashes within specific code blocks.</p>
<p>It enhances code modularity and helps you write more maintainable and predictable JavaScript code. Understanding block scope is essential for efficient and organized coding.</p>
<h2 id="heading-scope-chain">Scope Chain</h2>
<p>The scope chain in JavaScript is like a stack of transparent sheets, each representing a different scope. These sheets are stacked on top of each other, with the global scope at the bottom.</p>
<p>When you reference a variable, JavaScript searches for it starting from the top sheet (the current local or block scope) and moves down through the sheets, looking in each scope until it finds the variable.</p>
<p>This process of searching for variables through multiple scopes is known as the "scope chain."</p>
<p>Imagine you have a pile of sheets representing different scopes, like a book with many pages. Each page contains some information (variables) that you can access.</p>
<p>When you need a piece of information, you start from the current page, and if it's not there, you turn the pages until you find it.</p>
<h3 id="heading-how-javascript-resolves-variable-references">How JavaScript Resolves Variable References</h3>
<p>To understand the scope chain better, consider the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> globalVariable = <span class="hljs-string">"I'm global"</span>;

<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">var</span> outerVariable = <span class="hljs-string">"I'm in outer scope"</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-keyword">var</span> innerVariable = <span class="hljs-string">"I'm in inner scope"</span>;
    <span class="hljs-built_in">console</span>.log(innerVariable); <span class="hljs-comment">// Access innerVariable</span>
    <span class="hljs-built_in">console</span>.log(outerVariable); <span class="hljs-comment">// Access outerVariable</span>
    <span class="hljs-built_in">console</span>.log(globalVariable); <span class="hljs-comment">// Access globalVariable</span>
  }

  innerFunction();
}

outerFunction();
</code></pre>
<p>In this example, the <code>innerFunction</code> can access variables from its local scope (for example, <code>innerVariable</code>), the outer scope (for example, <code>outerVariable</code>), and the global scope (for example, <code>globalVariable</code>). JavaScript follows the scope chain to find these variables.</p>
<h3 id="heading-understanding-lexical-scope">Understanding Lexical Scope</h3>
<p>The scope chain in JavaScript follows a principle known as lexical (or static) scoping.</p>
<p>Lexical scoping means that the scope of a function is determined by where the function is declared, not where it's called.</p>
<p>This concept is similar to how a book's pages are ordered and arranged in a specific sequence, with each page having access to the previous ones.</p>
<p>Consider the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-string">"I'm global"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">firstFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> a = <span class="hljs-string">"I'm in firstFunction"</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">secondFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// Accesses a from firstFunction, not the global a</span>
  }

  secondFunction();
}

firstFunction();
</code></pre>
<p>In this example, even though <code>secondFunction</code> is called from within <code>firstFunction</code>, it still references the <code>a</code> variable from the scope where it was declared (lexical scope), which is the <code>firstFunction</code>.</p>
<h3 id="heading-nested-scopes-and-their-impact-on-the-scope-chain">Nested Scopes and Their Impact on the Scope Chain</h3>
<p>The scope chain can become more complex when you have nested functions or code blocks.</p>
<p>Each new layer introduces a new sheet in the stack. Variables in inner scopes can shadow (hide) variables with the same name in outer scopes.</p>
<p>Here's an example to illustrate this concept:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>;

<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> x = <span class="hljs-number">20</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> x = <span class="hljs-number">30</span>;
    <span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// Accesses x from the innermost scope (x = 30)</span>
  }

  inner();
  <span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// Accesses x from the outer scope (x = 20)</span>
}

outer();
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// Accesses x from the global scope (x = 10)</span>
</code></pre>
<p>In this code, each scope has its own <code>x</code> variable, and the scope chain determines which one is accessed.</p>
<p>Understanding the scope chain and how it follows the rules of lexical scoping is crucial for effectively managing variable access and avoiding unexpected variable clashes in complex JavaScript programs.</p>
<p>It's like flipping through a book's pages to find the information you need in the right order.</p>
<h2 id="heading-closures-and-function-scope">Closures and Function Scope</h2>
<p>Closures are a fascinating and powerful concept in JavaScript that involves the interplay of function scope and the scope chain.</p>
<p>Think of closures as little "bundles" of code that encapsulate both a function and the variables it needs to work with.</p>
<p>These bundles are like self-contained units of functionality that can be stored, passed around, and executed independently.</p>
<p>Analogously, consider a lunchbox that contains a sandwich and some ingredients. The lunchbox keeps everything together and allows you to enjoy your meal when and where you like.</p>
<p>In a similar way, closures bundle a function with its associated variables, making them portable and self-contained.</p>
<h3 id="heading-how-function-scope-and-closures-are-related">How Function Scope and Closures are Related</h3>
<p>In JavaScript, a closure is formed when a function is declared within another function, and the inner function has access to the variables of the outer function.</p>
<p>This behavior is a result of function scope and the scope chain.</p>
<p>Let's look at an example to illustrate closures:</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">var</span> outerVariable = <span class="hljs-string">"I'm in outerFunction"</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-comment">// Accesses outerVariable from the outer scope</span>
  }

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

<span class="hljs-keyword">var</span> closure = outerFunction();
closure(); <span class="hljs-comment">// This still has access to outerVariable</span>
</code></pre>
<p>In this code, <code>innerFunction</code> is declared inside <code>outerFunction</code>, forming a closure.</p>
<p>When <code>outerFunction</code> is called and assigned to the <code>closure</code> variable, it retains access to <code>outerVariable</code> even after <code>outerFunction</code> has completed.</p>
<p>This is the essence of a closure: the inner function remembers the scope in which it was created and can access its variables even when the outer function has finished executing.</p>
<h3 id="heading-practical-examples-of-closures">Practical Examples of Closures</h3>
<p>Closures are used in various scenarios in JavaScript. Here are a few practical examples:</p>
<ul>
<li><strong>Data Encapsulation</strong>: Closures allow you to encapsulate data and behavior. It's like a sealed envelope containing information that can only be accessed through specific methods.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">increment</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      count++;
    },
    <span class="hljs-attr">getCount</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">var</span> counter = createCounter();
counter.increment();
<span class="hljs-built_in">console</span>.log(counter.getCount()); <span class="hljs-comment">// Accesses the count variable via closures</span>
</code></pre>
<ul>
<li><strong>Event Handlers</strong>: Closures are commonly used in event handling. An event handler function can "remember" the context in which it was created, making it easy to access variables when handling events.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setupEvent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> message = <span class="hljs-string">"Hello, world!"</span>;
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    alert(message); <span class="hljs-comment">// Accesses the message variable via a closure</span>
  });
}
</code></pre>
<ul>
<li><strong>Module Pattern</strong>: Closures can be used to create modular and organized code structures. You can hide internal implementation details and expose only the necessary interface.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</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-keyword">var</span> privateVariable = <span class="hljs-string">"I'm private"</span>;

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">publicFunction</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(privateVariable); <span class="hljs-comment">// Accesses privateVariable via a closure</span>
    }
  };
})();

<span class="hljs-built_in">module</span>.publicFunction();
</code></pre>
<p>Closures are a fundamental concept that enables advanced JavaScript programming techniques and is essential for understanding topics like callbacks, promises, and asynchronous programming.</p>
<p>They provide a means to create self-contained, reusable, and secure code components, much like the way a lunchbox contains everything you need for a meal.</p>
<h2 id="heading-scope-best-practices">Scope Best Practices</h2>
<p>Effective management of scope is a fundamental aspect of writing clean, maintainable, and efficient JavaScript code.</p>
<p>By following best practices, you can avoid common pitfalls, reduce the likelihood of bugs, and improve the overall quality of your code.</p>
<p>Here are some scope-related best practices:</p>
<h3 id="heading-tips-for-avoiding-common-scope-related-issues">Tips for Avoiding Common Scope-Related Issues</h3>
<ul>
<li><p><strong>Limit Global Variables</strong>: Minimize the use of global variables. Overusing them can lead to naming conflicts and make it challenging to maintain your code as it grows.Only use global scope for variables that truly need to be accessed from various parts of your application.</p>
</li>
<li><p><strong>Use Strict Mode</strong>: Enable strict mode in your JavaScript code. Strict mode helps catch common programming mistakes and "unsafe" actions, including accidentally creating global variables.</p>
</li>
</ul>
<p>To enable strict mode, add the following line to the top of your scripts:</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>;
</code></pre>
<ul>
<li><strong>Avoid Variable Shadowing</strong>: Be cautious when reusing variable names in nested scopes, as this can lead to confusion and unexpected behavior. Use descriptive variable names and minimize shadowing to improve code readability.</li>
</ul>
<h3 id="heading-the-importance-of-minimizing-global-variables">The Importance of Minimizing Global Variables</h3>
<ul>
<li><p><strong>Data Encapsulation</strong>: Encapsulate your data within functions and modules. By keeping data within local or function scope, you reduce the risk of unintended interference and make your code more modular and maintainable.</p>
</li>
<li><p><strong>Avoid Side Effects</strong>: Minimizing global variables helps reduce unintended side effects in your code. Global variables can be modified from multiple locations, making it difficult to trace the source of changes and leading to unexpected results.</p>
</li>
</ul>
<h3 id="heading-using-appropriate-variable-names-for-clarity">Using Appropriate Variable Names for Clarity</h3>
<ul>
<li><p><strong>Descriptive Naming</strong>: Use clear and descriptive variable names that convey their purpose. This practice is especially crucial in global scope, where variable names can affect multiple parts of your code. Descriptive names improve code understanding and maintainability.</p>
</li>
<li><p><strong>Avoiding Single-Letter Variables</strong>: While single-letter variable names like <code>i</code> and <code>j</code> are common in loops, try to use them sparingly outside of loop contexts. Meaningful variable names enhance code readability and make it easier for you and others to understand your code.</p>
</li>
</ul>
<h3 id="heading-when-to-use-different-types-of-scope">When to Use Different Types of Scope</h3>
<ul>
<li><p><strong>Global Scope</strong>: Use global scope only for variables that genuinely need to be accessed throughout your application. Global variables should be rare exceptions and carefully managed.</p>
</li>
<li><p><strong>Local and Block Scope</strong>: Embrace local and block scope to keep variables isolated and contained. Use local scope within functions and block scope for variables within specific code blocks like loops and conditional statements.</p>
</li>
<li><p><strong>Closures</strong>: Utilize closures for encapsulating data and behavior when necessary. Closures provide a powerful way to create self-contained units of functionality and are particularly valuable for data privacy and modularity.</p>
</li>
</ul>
<p>Mastering scope in JavaScript is crucial for writing efficient and maintainable code.</p>
<p>By following these best practices, you can minimize common scope-related issues, reduce the risk of bugs, and create code that is easier to read, understand, and maintain.</p>
<p>Keep in mind that scope is not just a technical aspect of programming. It also plays a pivotal role in writing code that is both reliable and scalable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Scope in JavaScript is a fundamental concept that influences the behavior and structure of your code.</p>
<p>Understanding the intricacies of global, local, and block scope, as well as the scope chain, is essential for becoming a proficient JavaScript developer.</p>
<p>In this article, we've explored these concepts in depth, providing analogies and code examples to aid your understanding.</p>
<p>JavaScript's scope mechanisms are like the foundation of a building – they determine the structure, stability, and functionality of your code.</p>
<p>The scope you choose and how you manage it can significantly impact the quality and maintainability of your projects.</p>
<p>As you conclude this exploration of scope, it's crucial to reiterate some key takeaways:</p>
<ol>
<li><p><strong>Scope is a Crucial Concept</strong>: Scope is not just a technicality. It's a core concept that influences the way you write, organize, and maintain your JavaScript code.</p>
</li>
<li><p><strong>Global, Local, and Block Scope</strong>: JavaScript offers different types of scope, each serving specific purposes. Global scope provides broad accessibility, local scope offers isolation, and block scope controls visibility within specific code blocks.</p>
</li>
<li><p><strong>Scope Chain and Closures</strong>: Understanding the scope chain is essential for comprehending how JavaScript resolves variable references. Closures, which leverage function scope, play a pivotal role in encapsulating data and behavior.</p>
</li>
<li><p><strong>Best Practices Matter</strong>: Following scope best practices, such as minimizing global variables, using descriptive variable names, and embracing local and block scope, will lead to cleaner and more maintainable code.</p>
</li>
</ol>
<p>As you work on real-world projects, keep these scope-related principles in mind, and apply them to create code that is not only robust but also adaptable to the evolving demands of web development.</p>
<p>Continue exploring and practicing these concepts, and you'll be well on your way to JavaScript mastery.</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>
        
    </channel>
</rss>
