Ever heard of the term “closure” in JavaScript and thought, “That sounds complex”? You’re not alone. But the truth is — closures are simple but powerful, and they play a major role behind the scenes in many JavaScript features like callbacks, private variables, and currying.
In this blog, we’ll break down closures in a fun and easy way with examples you’ll remember forever.
🧠 What is a Closure?
A closure is when a function remembers the variables from the place where it was created, even if it’s called somewhere else.
📦 Think of It Like a Backpack
Imagine a function carrying a backpack of variables with it. Even if that function is used later or somewhere else, it still has access to what’s inside that backpack.
✅ Basic Example
javascriptCopyEditfunction outer() {
let name = "Codey";
function inner() {
console.log("Hello, " + name);
}
return inner;
}
const greet = outer(); // outer() runs and returns inner()
greet(); // Outputs: Hello, Codey
Even though
outer()
has finished running,inner()
still remembersname
.
🔒 Creating Private Variables
Closures allow us to protect data — variables that cannot be accessed directly from outside.
javascriptCopyEditfunction createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
count
is private — only the inner function can access it.
🧰 Real Use Cases of Closures
- Event handlers
- setTimeout / setInterval
- Data privacy (private state)
- Currying and partial functions
- Maintaining state without classes
🧪 Closure with setTimeout
javascriptCopyEditfunction delayLog() {
for (let i = 1; i <= 3; i++) {
setTimeout(function () {
console.log("i =", i);
}, i * 1000);
}
}
delayLog();
// Outputs:
// i = 1 (after 1s)
// i = 2 (after 2s)
// i = 3 (after 3s)
Because of closures and
let
, each timeout remembers its own copy ofi
.
❓ Why Do Closures Matter?
- Helps you manage memory and avoid polluting global scope
- Enables powerful patterns like modules and callbacks
- Used in frameworks (React Hooks rely on closures!)