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