Closures
Overview
A Closure is one of the most powerful, heavily tested, and least understood concepts in JavaScript.
A closure is formed when an inner function "remembers" the variables of its outer function, even after the outer function has completely finished executing and returned.
Normally, when a function finishes running, its local variables are destroyed by the Garbage Collector. But if an inner function still holds a reference to them, they are kept alive in a 'closure' memory bubble.
Syntax
function createCounter() {
let count = 0; // Private variable
// This inner function forms a Closure over 'count'
return function() {
count++;
return count;
}
}
const myCounter = createCounter();
// createCounter finishes executing! Its scope should be destroyed.
// BUT, myCounter STILL remembers 'count'!
console.log(myCounter()); // 1
console.log(myCounter()); // 2Common Pitfalls
- Creating closures inside
forloops usingvarinstead oflet. Becausevaris function-scoped, all closures created in the loop will share the exact samevarreference, meaning they will all point to the final state of the loop variable.
Interview Questions
Imagine a function is a backpack. When a function is born inside another function, it packs all the variables it needs from its parent into its backpack. Even when the parent function goes away, the child function still has its backpack with the variables inside.
1. Data privacy (Emulating private methods). 2. Currying and partial application. 3. Maintaining state in asynchronous callbacks.
Real-World Example
Emulating private variables in JavaScript. The variables inside the outer function cannot be modified directly from the outside, keeping them secure.
const atm = createATM(100);
atm.withdraw(50); // Valid
// atm.balance = 100000; // Impossible, 'balance' is hidden in a closure!Check Your Knowledge
Test your understanding of Closures with these quick questions.