<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged closures</title>
<link>https://coderlegion.com/tag/closures</link>
<description>Powered by Question2Answer</description>
<item>
<title>Demystifying Closures: JavaScript's Built-In Memory Backpacker</title>
<link>https://coderlegion.com/26574/demystifying-closures-javascripts-built-in-memory-backpacker</link>
<description>&lt;p&gt;Have you ever wondered how software remembers your preferences even after a process seems to have finished? In the world of programming, this magic is often performed by a core concept known as a &lt;strong&gt;closure&lt;/strong&gt;.&lt;/p&gt;
&lt;h4 id=&quot;what-is-a-closure-&quot;&gt;What is a Closure?&lt;/h4&gt;
&lt;p&gt;A closure is a fundamental programming feature where an inner function retains access to the variables of its outer function, even after that outer function has finished executing. It acts as a persistent link between a function and the environment in which it was born. This prevents the outer variables from being cleared out of your computer's active memory.&lt;/p&gt;
&lt;h4 id=&quot;the-backpack-analogy&quot;&gt;The Backpack Analogy&lt;/h4&gt;
&lt;p&gt;To understand how this works, imagine you are planning a long hike. Before you walk out the front door of your house (which represents the &lt;strong&gt;outer function&lt;/strong&gt;), you pack a few essential items into your backpack (representing the &lt;strong&gt;variables&lt;/strong&gt;)—a water bottle, a compass, and some trail mix.&lt;/p&gt;
&lt;p&gt;Once you step outside, the door locks behind you. The house is closed, and you can no longer go back inside. However, as you walk down the trail (representing the &lt;strong&gt;inner function&lt;/strong&gt;), you still have complete access to the water bottle, compass, and trail mix. You do not need to reopen the house to use them because they are sealed in your backpack.&lt;/p&gt;
&lt;p&gt;In this analogy, the backpack is the closure. It is a portable envelope of data that the hiker (the inner function) carries along, regardless of where they travel or how much time has passed since they left home.&lt;/p&gt;
&lt;h4 id=&quot;why-closures-matter-in-daily-software-engineering&quot;&gt;Why Closures Matter in Daily Software Engineering&lt;/h4&gt;
&lt;p&gt;For software engineers, closures are not just an academic curiosity; they are a vital tool used daily to write safe, maintainable code.&lt;/p&gt;
&lt;p&gt;One of the biggest challenges in building large applications is avoiding &quot;global namespace pollution.&quot; If every piece of data in an application is accessible to every function, it is highly likely that one function will accidentally overwrite data being used by another. This leads to unpredictable bugs.&lt;/p&gt;
&lt;p&gt;Engineers use closures to create &lt;strong&gt;private variables&lt;/strong&gt;. By nesting a function inside another, we can shield variables from the outside world. This is called encapsulation. It allows developers to build robust tools and software libraries where internal settings are protected from being modified by external scripts.&lt;/p&gt;
&lt;h4 id=&quot;seeing-closures-in-action&quot;&gt;Seeing Closures in Action&lt;/h4&gt;
&lt;p&gt;Let's look at a simple JavaScript example that demonstrates how a closure keeps a variable alive:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;function createCounter() {
  // This variable is protected inside the outer function
  let count = 0;

  // This inner function is returned, creating a closure
  return function() {
    count += 1;
    return count;
  };
}

// myCounter now holds the inner function
const myCounter = createCounter();

console.log(myCounter()); // Output: 1
console.log(myCounter()); // Output: 2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, when we run &lt;code&gt;createCounter()&lt;/code&gt;, it sets &lt;code&gt;count&lt;/code&gt; to &lt;code&gt;0&lt;/code&gt; and returns the inner function. Once it returns, the &lt;code&gt;createCounter&lt;/code&gt; function has finished executing. Normally, its internal variables would be deleted from memory. However, because the inner function still references &lt;code&gt;count&lt;/code&gt;, JavaScript creates a closure. Every time we call &lt;code&gt;myCounter()&lt;/code&gt;, it still has access to that private &lt;code&gt;count&lt;/code&gt; variable, updating it seamlessly.&lt;/p&gt;
&lt;h4 id=&quot;the-takeaway&quot;&gt;The Takeaway&lt;/h4&gt;
&lt;p&gt;Closures are not a complex design pattern you need to manually install; they are a natural, built-in feature of how modern programming languages manage memory. By understanding that functions carry their original environment with them, you can write cleaner, self-contained code that keeps your data secure.&lt;/p&gt;
&lt;hr&gt;
&lt;h4 id=&quot;resources&quot;&gt;Resources&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;GitHub Repository:&lt;/strong&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/Saurav-TB-Pandey/react-hook-lab&quot;&gt;react-hook-lab&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;react-hook-lab:&lt;/strong&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.npmjs.com/package/react-hook-lab&quot;&gt;npm package&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Connect with me on LinkedIn:&lt;/strong&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.linkedin.com/in/pandeysaurav/&quot;&gt;Saurav Pandey&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;p&gt;&lt;em&gt;Originally published on my blog. You can &lt;a rel=&quot;nofollow&quot; href=&quot;https://sauravtbpandey.blogspot.com/2026/09/locking-in-state-why-javascript.html&quot;&gt;read the alternative breakdown here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/26574/demystifying-closures-javascripts-built-in-memory-backpacker</guid>
<pubDate>Wed, 09 Sep 2026 08:23:04 +0000</pubDate>
</item>
<item>
<title>Understanding Stateful Functions Through JavaScript Closures</title>
<link>https://coderlegion.com/9611/understanding-stateful-functions-through-javascript-closures</link>
<description>&lt;p&gt;Closure In JavaScript is a function that retains access to variables from its outer scope, even after the outer function has finished executing.&lt;/p&gt;
&lt;p&gt;This definition may seem complicated at the first, but don’t worry in this article— we will Learn how JavaScript closures transform functions from stateless to stateful, with practical examples and the mental model that makes everything click.&lt;/p&gt;
&lt;p&gt;in this article we will cover:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#why-we-need-closures&quot;&gt;Why We Need Closures&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#what-is-lexical-scope&quot;&gt;What is Lexical Scope&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;[Understanding Closures and Lexical Scope] (#understanding-of-closures-and-lexical-scope) &lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#working-with-closure&quot;&gt;Working with Closure&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#use-cases-for-closures&quot;&gt;Use Cases for Closures&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#final-remarks&quot;&gt;Final Remarks&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;why-we-need-closures&quot;&gt;Why We need closures&lt;/h2&gt;
&lt;p&gt;Closures are very important to know for you to be able to use today's modern frameworks like React, Redux library.&lt;/p&gt;
&lt;p&gt;In this guide we will go through the inner workings of closures and also provide you with use-cases and application of closures in React framework and in real world example using closures.&lt;/p&gt;
&lt;p&gt;Advantages of closures includes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Helps keep the function pure without mutating the external of it.&lt;/li&gt;
&lt;li&gt;Helps make variable private the scope they are declare in.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;what-is-lexical-scope-&quot;&gt;What is Lexical scope:&lt;/h2&gt;
&lt;h3 id=&quot;lexical-scope-by-definition&quot;&gt;Lexical Scope by definition&lt;/h3&gt;
&lt;p&gt;Lexical scope in JavaScript are rules that determines how and where the variable can be accessed in your program.&lt;/p&gt;
&lt;h3 id=&quot;lexical-scope-under-the-hood&quot;&gt;Lexical Scope under the hood&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;lexical scope&lt;/code&gt; under the hood is an &lt;code&gt;object&lt;/code&gt; in JavaScript’s scope either in a function or any JavaScript scope you may think of &lt;/p&gt;
&lt;p&gt;that object which we call &lt;code&gt;Lexical&lt;/code&gt; scope keeps track of:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the variable in that scope.&lt;/li&gt;
&lt;li&gt;the value of &lt;code&gt;this&lt;/code&gt; of that scope.&lt;/li&gt;
&lt;li&gt;the pointer that points to the outer lexical scope if there any if there is no other scope above that the point is null&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;so, when we have a function that looks like this&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;let x = 10

function test(){
let y = 4
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This function lexical scope would look like this:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5syxqen8r6avj2m47bbk.png&quot; alt=&quot;Image description&quot;&gt;&lt;/p&gt;
&lt;p&gt;as we demonstrated in this diagram each scope has its own lexical scope which points to the outer lexical scope above it.&lt;/p&gt;
&lt;p&gt;when in the &lt;code&gt;test()&lt;/code&gt; you try to access the variable &lt;code&gt;x&lt;/code&gt; JavaScript will look for it in the lexical scope of &lt;code&gt;test()&lt;/code&gt; if it is not there, it will then look in its outer lexical scope pointer which is the global one and if we have &lt;code&gt;x&lt;/code&gt;  there we will then access to &lt;code&gt;x&lt;/code&gt; and use it inside our function of &lt;code&gt;test()&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;What happens when we don’t have it, we will continue go up the tree and until we hit the lexical scope that’s points to null and that’s when you get the error saying: &lt;code&gt;Uncaught ReferenceError: x is not defined&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;function test(){
let y = 4
return x
}

console.log(test()) //Uncaught ReferenceError: x is not defined
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;understanding-closures-and-lexical-scope-&quot;&gt;Understanding Closures and Lexical scope:&lt;/h3&gt;
&lt;p&gt;To understand closures, we first need to understand how the normal function works under the hood. this will helps knowing what options with closure that are limited when using usual function.&lt;/p&gt;
&lt;p&gt;A normal function when its execution finishes there is a memory management mechanism in JavaScript that is known as &lt;code&gt;garbage collection&lt;/code&gt; .&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Garbage collection:&lt;/strong&gt; is a mechanism for JavaScript to clean up the allocated memory for non-primitive data types when they are no longer in use, again if you don’t know how functions and non-primitive data types how are stored in memory, I have an article which talks about it which you can find &lt;a rel=&quot;nofollow&quot; href=&quot;https://dev.to/jaboarnoldlandry/lets-discuss-deep-and-shallow-clone-in-javascript-3om7&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;garbage collection removes the allocated memory when the function is no longer in use makes the functions after execution reset all its variables and values declared with in its block scope of a function or the passed argument to the function.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;function test(){
let y = 4
return y+= 1
}

console.log(test()) // 5
console.log(test()) // 5
console.log(test()) // 5
console.log(test()) // 5
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;No matter how long we call the function the result will always be the same unless we have variable  &lt;code&gt;y&lt;/code&gt; in global scope&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;let y = 4;

function test(){
return y+= 1
}

console.log(test()) // 5
console.log(test()) // 6
console.log(test()) // 7
console.log(test()) // 8
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What happens here is the garbage collection will clear out any allocated space that is no longer has reference with global object in case of browser the global object is the &lt;code&gt;window&lt;/code&gt; object, When the function finished executing it cuts reference and ties to the window object which then makes it eligible for garbage collected and wipe out all of its declared variable and passed argument if there are any.&lt;/p&gt;
&lt;p&gt;But when we have declared a variable in a global scope, the declared variable connection with the &lt;code&gt;window&lt;/code&gt; object will stay forever until you remove the variable from the global scope, which is why the variable is updated to a new value every time we call the function, because the variable state is updating.&lt;/p&gt;
&lt;p&gt;To give you a better mental model shift around these concepts you should think of them like:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;stateless function:&lt;/strong&gt; a function that has no access to variable(s) outside of its scope the function variables are &lt;strong&gt;stateless&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;stateful function:&lt;/strong&gt; the function with access variable(s) from outside of its scope they have state which can be tracked and updated over time which makes them persists data and update as we go.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;working-with-closure-&quot;&gt;Working with closure:&lt;/h2&gt;
&lt;p&gt;You know how the whole life cycle of execution of functions and a knowledge of how lexical scope works.&lt;/p&gt;
&lt;p&gt;I want you to take a look at this snippet:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;function counter(){
let n = 0
return function(){
return n += 1
}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;this is the most common example you will see online of working with closures, and yeah this is how we create a closure we return a function and wrap it inside another function so when we call the outer function in our case &lt;code&gt;counter&lt;/code&gt; it will return  another function which will look like this &lt;code&gt;[Function (anonymous)]&lt;/code&gt; .&lt;/p&gt;
&lt;p&gt;because as we have seen in the example above the &lt;code&gt;counter&lt;/code&gt; returns a function, now the returned function has reference to its outer scope variable &lt;code&gt;n&lt;/code&gt; thus making connection with its lexical scope, since we have the connection with variable outside of the scope of the inner function it will persist the state of data.&lt;/p&gt;
&lt;p&gt;remember the stateful mental model&lt;strong&gt; it states that &lt;/strong&gt;“the function with access to variable(s) from outside of its scope they have state which can be tracked and updated over time which makes them persists data and update as we go.”**&lt;/p&gt;
&lt;p&gt;It means that since we have the reference to the variable &lt;code&gt;n&lt;/code&gt; garbage collection will not remove variable &lt;code&gt;n&lt;/code&gt; from the memory because there is some function that is referencing it,&lt;/p&gt;
&lt;p&gt;The outer function will be removed but &lt;code&gt;n&lt;/code&gt; will stay because of the connection it has with the inner function and that’s why mostly you will hear people define closure as &lt;strong&gt;“a function that retains its lexical scope even after its outer function has finished executing”&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;now because of closures we’ve made variable &lt;code&gt;n&lt;/code&gt; from &lt;strong&gt;stateless&lt;/strong&gt; to &lt;strong&gt;state preservation&lt;/strong&gt; and now we can use the function to increment numbers we want, and here is how we execute the closure function&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;const count = counter() // assing the return function to a new variable
// use that variable to get the counts from the inner function
console.log(count()) //1
console.log(count()) //2
console.log(count()) //3
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;tricky-question&quot;&gt;Tricky Question&lt;/h4&gt;
&lt;p&gt;Try and figure out what is a closure from the below 2 snippets &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A&lt;/strong&gt;                                                                                                    &lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;function outer(){
let p = 0;
return function(){
return p += 1
}
}
const results = outer()
console.log(results()) // 1
console.log(results()) // 2
console.log(results()) // 3
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;B&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;function outer(){
return function(){
    let p = 0;
return p += 1
}
}
const results = outer()
console.log(results()) // 1
console.log(results()) // 1
console.log(results()) // 1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Well option &lt;strong&gt;A&lt;/strong&gt; is the real answer because it has reference to its outer scope while &lt;strong&gt;B&lt;/strong&gt; is returning another function true, &lt;/p&gt;
&lt;p&gt;but we are declaring variable within that function which means the moment the function finishes executing garbage collection will wipe out everything from &lt;strong&gt;function B&lt;/strong&gt; &lt;/p&gt;
&lt;p&gt;remember the stateless mental model: it states that &lt;strong&gt;“a function that has no access to variable(s) outside of its scope the function variables are stateless”&lt;/strong&gt;&lt;/p&gt;
&lt;h2 id=&quot;use-cases-for-closures&quot;&gt;Use Cases for Closures&lt;/h2&gt;
&lt;p&gt;Let’s try to explore one practical use cases for closures that feels more real and makes sense to understand closure.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example for use Case:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;suppose we are creating a function that lists the names of members of our app and the country they are representing; with the stateless way we can create our function like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;function introduceYou(name, country){
return `Hi I am ${name} and I am representing ${country}`
}

console.log(introduceYou('Jabo', 'Rwanda') // Hi I am Jabo and I am respresenting Rwanda
console.log(introduceYou('Arnold', 'Rwanda') // Hi I am Arnold and I am respresenting Rwanda 
console.log(introduceYou('Landry', 'Rwanda') // Hi I am Landry and I am respresenting Rwanda 
console.log(introduceYou('John', 'Rwanda') // Hi I am John and I am respresenting Rwanda 
console.log(introduceYou('Abdul', 'UAE') // Hi I am Abdul and I am respresenting UAE 
console.log(introduceYou('Jane', 'USA') // Hi I am Jane and I am respresenting USA 
console.log(introduceYou('Doe', 'USA') // Hi I am Doe and I am respresenting USA 
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;problems-in-changing-the-existing-structure&quot;&gt;Problems in Changing the existing structure&lt;/h4&gt;
&lt;p&gt;This approach works, but here’s a catch, you came up with the idea like you know what let instead use the city names instead of country names to change this would look very tedious say you have a thousand representing &lt;strong&gt;Rwanda,&lt;/strong&gt; and millions representing &lt;strong&gt;USA.&lt;/strong&gt;&lt;/p&gt;
&lt;h4 id=&quot;solution-for-the-change&quot;&gt;Solution for the change&lt;/h4&gt;
&lt;p&gt;it would be hard to change all of those places and to be honest it is time consuming, but there is a solution , you can use closure to reference the thing that is common to the data we trying to capture in our case &lt;code&gt;country&lt;/code&gt; some users may have the same country or many of them so we will make that a default reference that will stay in memory for as long as we wish to and this will make it easier changing it to something new like city&lt;/p&gt;
&lt;h4 id=&quot;closure-solution-implementation&quot;&gt;closure solution implementation&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt;function introduceYou(locaction){
return function user(name){
return `Hi I am ${name} and I am representing ${location}`
}
}

//now we create a function that will handle people from different region

let rwandaUsers = introduceYou(&quot;Rwanda&quot;)
let americanUsers = IntroduceYou(&quot;USA&quot;)
let uaeUsers = IntroduceYou(&quot;UAE&quot;)

//and now we create a function for users based on the variable country we created

console.log(rwandaUsers(&quot;Jabo&quot;)) // Hi I am Jabo and I am respresenting Rwanda
console.log(rwandaUsers(&quot;Arnold&quot;)) // Hi I am Arnold and I am respresenting Rwanda
console.log(americanUsers(&quot;Jane&quot;)) // Hi I am Jane and I am respresenting USA
console.log(uaeUsers(&quot;Abdul&quot;)) // Hi I am Abdul and I am respresenting UAE
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;now if you want to change to their city all we need to be go where we’ve declared a certain user of a certain country and change the passed argument to be the city instead of country&lt;/p&gt;
&lt;p&gt;example (let’s change &lt;code&gt;rwandaUsers&lt;/code&gt; to use the city &lt;strong&gt;Kigali&lt;/strong&gt; instead)&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-jsx&quot;&gt; rwandaUsers = introduceYou(&quot;Kigali&quot;)

console.log(rwandaUsers(&quot;Jabo&quot;)) // Hi I am Jabo and I am respresenting Kigali
console.log(rwandaUsers(&quot;Arnold&quot;)) // Hi I am Arnold and I am respresenting Kigali
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;final-remarks&quot;&gt;Final Remarks&lt;/h2&gt;
&lt;p&gt;When I was preparing this article, I found that React states are built using closures which links back to that mental model shift for &lt;strong&gt;stateless&lt;/strong&gt; and &lt;strong&gt;stateful function&lt;/strong&gt; I shared with you, those mental model helped me realize why React state are called &lt;code&gt;state&lt;/code&gt; and how they are able to persist data throughout component life cycle.&lt;/p&gt;
&lt;p&gt;I hope this article gave you both understanding and confidence with closures. If you found it valuable, please share it with someone who's struggling with this concept—it might be the explanation that finally makes it click for them.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/9611/understanding-stateful-functions-through-javascript-closures</guid>
<pubDate>Tue, 13 Jan 2026 00:27:33 +0000</pubDate>
</item>
</channel>
</rss>