Closures in JavaScript: The Wizard's Secret Chest

Chandan Singh - Oct 18 '23 - - Dev Community

In the magical realm of JavaScript, where functions and objects dance together to create the enchanted web applications we use daily, there lies a secret that many novice sorcerers may find mystifying: the concept of closures. Picture this – a wizard has a secret chest, and within this chest, he keeps his most precious belongings, protecting them from the outside world. This chest, my dear reader, can be likened to closures in the world of JavaScript.

The Enchantment Begins: What is a Closure?

A closure is not just a function; it represents the combination of a function bundled together with references to its surrounding state or lexical environment. Think of it like our wizard's magical pouch: even as the wizard journeys through various realms, the pouch retains enchanted items (variables) from places the wizard has visited before.

Crafting Your First Closure

Let's embark on a magical journey to craft our first closure:


function wizardSpell() {
    let secretPotion = "Elixir of Eternity";

    function revealPotion() {
        return secretPotion;
    }

    return revealPotion;
}

let unveilTheSecret = wizardSpell();
console.log(unveilTheSecret()); // "Elixir of Eternity"
Enter fullscreen mode Exit fullscreen mode

In the code above, revealPotion is a closure. Even after wizardSpell has executed and returned, revealPotion still has access to secretPotion. When we invoke unveilTheSecret(), it reveals the secret potion, showcasing the magic of closures.

Why Are Closures Enchanting?

  1. Private Variables: Closures allow us to emulate private variables, which aren't natively supported in JavaScript. The secretPotion in our example acts as a private variable.
  2. Dynamic Function Generation: They can be used to create functions on the fly during execution.
  3. Maintaining State: Often used in JavaScript libraries to maintain state without exposing the internals.

Beware the Dark Arts: Pitfalls of Closures

While closures are a potent tool in our arsenal, they must be wielded with care:

  1. Memory Overuse: If not managed correctly, closures can lead to overconsumption of memory as they retain access to the outer function’s variables, which can prevent them from being garbage collected.
  2. Overhead: Overusing closures can sometimes lead to increased complexity in code.

Conclusion: The Power Within

Like the wizard's chest guarding its secrets, closures in JavaScript protect and provide access to an outer function’s scope. As budding JavaScript sorcerers, understanding closures and their power can truly elevate your magical coding prowess.

Further Reading: For those eager to dive deeper into the mystical world of closures, the MDN documentation on Closures is an excellent tome to explore. 📖🔮

Sorcerer’s Assignments: Test Your Magic

  • Secret Conversations: Craft a function that takes a name as its argument and returns another function. When you invoke the inner function with a message, it should console log the name and the message together, like a whisper between two wizards.
let whisperTo = secretMessenger("Merlin");
whisperTo("The dragon awakens!");  // Output: "Merlin hears: The dragon awakens!"
Enter fullscreen mode Exit fullscreen mode
  • The Enchanted Counter: Create a function that keeps track of the number of times it's been called using closures. Every time you invoke the function, it should return the incremented count.
let magicCounter = enchantedCounter();
console.log(magicCounter());  // Output: 1
console.log(magicCounter());  // Output: 2
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . .
Terabox Video Player