<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Closure with example - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Closure with example - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 09 May 2026 22:21:14 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/closure-with-example/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Closures in JavaScript – A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ By Matías Hernández Closures are a confusing JavaScript concept to learn, because it's hard to see how they're actually used.  Unlike other concepts such as functions, variables, and objects, you don't always use closures conscientiously and directly... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/closures-in-javascript/</link>
                <guid isPermaLink="false">66d46012246e57ac83a2c789</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Closure with example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 07 Jun 2021 18:18:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/English-Header-4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Matías Hernández</p>
<p>Closures are a confusing JavaScript concept to learn, because it's hard to see how they're actually used. </p>
<p>Unlike other concepts such as functions, variables, and objects, you don't always use closures conscientiously and directly. You don't say: Oh! Here I will use a closure as a solution.</p>
<p>But at the same time, you might have already used this concept a hundred times. Learning about closures is more about identifying when one is being used rather than learning a new concept.</p>
<h2 id="heading-what-is-a-closure-in-javascript">What is a closure in JavaScript?</h2>
<p>You have a closure when a function reads or modifies the value of a variable defined outside its context.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> value = <span class="hljs-number">1</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> data = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>]
    <span class="hljs-keyword">return</span> data.filter(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item % value === <span class="hljs-number">0</span>)
}
</code></pre>
<p>Here the function <code>doSomething</code> uses the variable <code>value</code>. But also the function <code>item =&gt; item % value === 0</code> can then be written like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>)</span>{
    <span class="hljs-keyword">return</span> item % value === <span class="hljs-number">0</span>
}
</code></pre>
<p>You use the value of the variable <code>value</code> that was defined outside of the function itself.</p>
<h2 id="heading-functions-can-access-values-out-of-context">Functions can access values out of context</h2>
<p>As in the previous example, a function can access and use values that are defined outside its "body" or context, for example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(count)
}
counter() <span class="hljs-comment">// print 1</span>
count = <span class="hljs-number">2</span>
counter() <span class="hljs-comment">// print 2</span>
</code></pre>
<p>This allows us to modify the value of the <code>count</code> variable from anywhere in the module. Then when the counter function is called, it will know how to use the current value.</p>
<h2 id="heading-why-do-we-use-functions"><strong>Why do we use functions?</strong></h2>
<p>But why do we use functions in our programs? Certainly it is possible – difficult, but possible – to write a program without using functions we define. So why do we create proper functions?</p>
<p>Imagine a piece of code that does something wonderful, whatever, and is made up of X number of lines.</p>
<pre><code><span class="hljs-comment">/* My wonderful piece of code */</span>
</code></pre><p>Now suppose you must use this <strong>wonderful piece of code</strong> in various parts of your program, what would you do?.</p>
<p>The "natural" option is to put this piece of code together into a set that can be reusable, and that reusable set is what we call a function. Functions are the best way to reuse and share code within a program.</p>
<p>Now, you can use your function as many times as possible. And, ignoring some particular cases, calling your function N times is the same as writing that <strong>wonderful piece of code</strong> N times. It is a simple replacement.</p>
<h2 id="heading-but-where-is-the-closure"><strong>But where is the closure?</strong></h2>
<p>Using the counter example, let's consider that as the <strong>wonderful piece of code.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(count)
}
counter() <span class="hljs-comment">// print 1</span>
</code></pre>
<p>Now, we want to reuse it in many parts, so we will "wrap" it in a function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wonderfulFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(count)
    }
    counter() <span class="hljs-comment">// print 1</span>
}
</code></pre>
<p>Now what do we have? A function: <code>counter</code> that uses a value that was declared outside it <code>count</code>. And a value: <code>count</code> that was declared in the <code>wonderfulFunction</code> function scope but that is used inside the <code>counter</code> function.</p>
<p>That is, we have a function that uses a value that was declared outside its context: <strong>a closure</strong>.</p>
<p>Simple, isn't it? Now, what happens when the function <code>wonderfulFunction</code> is executed? What happens to the variable <code>count</code> and the function <code>counter</code> once the <strong>parent</strong> function is executed? </p>
<p>The variables and functions declared in its body <em>"disappear"</em> (garbage collector).</p>
<p>Now, let's modify the example a bit:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wonderfulFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">1</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
        count++
        <span class="hljs-built_in">console</span>.log(count)
    }
   <span class="hljs-built_in">setInterval</span>(counter, <span class="hljs-number">2000</span>)
}
wonderfulFunction()
</code></pre>
<p>What will happen now to the variable and function declared inside <code>wonderfulFunction</code>? </p>
<p>In this example, we tell the browser to run <code>counter</code> every 2 seconds. So the JavaScript engine must keep a reference to the function and also to the variable that is used by it. Even after the parent function <code>wonderfulFunction</code> finishes its execution cycle, the function <code>counter</code> and the value count will still "<em>live"</em>.</p>
<p>This "effect" of having closures occurs because JavaScript supports the nesting of functions. Or in other words, functions are <strong>first class citizens</strong> in the language and you can use them like any other object: nested, passed as an argument, as a value of return, and so on.</p>
<h2 id="heading-what-can-i-do-with-closures-in-javascript"><strong>What can I do with closures in JavaScript?</strong></h2>
<h3 id="heading-immediately-invoked-function-expression-iife"><strong>Immediately-invoked Function Expression (IIFE)</strong></h3>
<p>This is a technique that was used a lot in the ES5 days to implement the "module" design pattern (before this was natively supported). The idea is to "wrap" your module in a function that is immediately executed.</p>
<pre><code class="lang-javascript">(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">arg1, arg2</span>)</span>{
...
...
})(arg1, arg2)
</code></pre>
<p>This lets you use private variables that can only be used by the module itself within the function – that is, it's allowed to emulate the access modifiers.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> <span class="hljs-built_in">module</span> = (<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">privateMethod</span> (<span class="hljs-params"></span>) </span>{
    }
    <span class="hljs-keyword">const</span> privateValue = <span class="hljs-string">"something"</span>
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">get</span>: privateValue,
      <span class="hljs-attr">set</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">v</span>) </span>{ privateValue = v }
    }
})()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

<span class="hljs-keyword">const</span> callInnerFunctions = callTheNumber();
<span class="hljs-built_in">console</span>.log(callInnerFunctions[<span class="hljs-number">0</span>]()); <span class="hljs-comment">// 0</span>
<span class="hljs-built_in">console</span>.log(callInnerFunctions[<span class="hljs-number">1</span>]()); <span class="hljs-comment">// 1</span>
</code></pre>
<p>Here, we have created separate scope for each iteration. You can use <code>console.dir(arrToStore)</code> to check the value of x in <code>[[scopes]]</code> for different array elements.</p>
<p>That’s it! I hope you can now say that you find closures interesting.</p>
<p>To read my other articles, check out my profile <a target="_blank" href="https://www.freecodecamp.org/news/author/anchal">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
