Unraveling the Magic of Closures in JavaScript

Unraveling the Magic of Closures in JavaScript

Β·

2 min read

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

Β