Unraveling the Magic of Closures in JavaScript
In the world of JavaScript, each time we run a function, it creates a fresh local memory (new execution context). It doesn't hold onto memories of previous runs. Once the function finishes executing, its local memory is wiped clean, leaving only the returned value behind. That's just how functions typically operate.
But what if we need to retain knowledge from previous executions?
Imagine having a counter function, you don't want it to start the count from 0 each time, that would be useless, that's where functions with memories "closure" come in very handy.
Closures allow functions to hold onto live data between executions. They remember what happened in previous runs, such as the count being at 1.
So, what does a closure look like? It's as simple as declaring and returning a function within another function. Take a look at this example:
function counter() {
let count = 0;
return function incrementCounter() {
count++;
console.log(count);
};
}
when ๐๐๐๐๐๐๐๐๐๐ช๐๐๐๐๐๐()
is declared inside ๐๐๐๐๐๐๐()
, it saves with it a hidden property [[๐๐๐๐๐]] that gets linked to local memory of ๐๐๐๐๐๐๐()
(in this case local memory contain the variable ๐๐๐๐๐).
The only way to access this captured memory is by invoking the ๐๐๐๐๐๐๐๐๐๐ช๐๐๐๐๐๐
function, so whenever we run the function, ๐๐๐๐๐ is updated since it keeps its value from the previous running.
Think of it as a backpack that holds your data. Each time you run the function, you open the backpack and retrieve what you need, allowing you to maintain and update data between function calls.
const generateCounter = counter();
generateCounter(); // Output: 1
generateCounter(); // Output: 2
generateCounter(); // Output: 3
This magical property is often referenced as "PLSRD" (Persistent Lexically Scoped Referenced Data), because when we run the function, we lexically grab the scope and attach it to that [[scope]] property of ๐๐๐๐๐๐๐๐๐๐ช๐๐๐๐๐๐()
Closures empower us to create efficient, stateful functions in JavaScript, and understanding how they work is a valuable skill for any developer. โจ
#JavaScript #Closures #Programming #WebDevelopment #CodeMagic
Subscribe to my newsletter
Read articles from mahi samia directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
mahi samia
mahi samia
hey there ๐ i'm Samia, a Backend developer turning to frontend world. i used to work as a Laravel and PHP developer for 3 and half years, in that journey, i had to deal from time to time with some frontend tasks, like fixing responsiveness or converting some psd files into HTML & CSS, that was when i fall in love with it. I loved the idea of turning creative and beautiful design into reality, so i made that career switch and now turning fully to Frontend development. Feel free to checkout my journey on Instagram or just pass Hi