🧵 What Is a Closure in JavaScript (And Why It Matters)?

Closures are one of the most asked-about — and misunderstood — concepts in JavaScript interviews.
Let’s simplify it.
🔍 What’s a Closure?
A closure happens when a function "remembers" the variables from its lexical scope, even after that outer function has finished running.
🧪 Example:
jsCopyEditfunction outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3
Even though outer()
is done running, the inner()
function remembers the variable count
.
That’s a closure!
🧠 Why Are Closures Useful?
✅ Data privacy (like private variables)
✅ Building factories and utilities
✅ Avoiding global variables
✅ Powering functions like
setTimeout
, event handlers, and more
🎯 Real-World Use
jsCopyEditfunction createLogger(prefix) {
return function(message) {
console.log(`[${prefix}] ${message}`);
};
}
const errorLog = createLogger("ERROR");
errorLog("Something went wrong"); // [ERROR] Something went wrong
Closures make this possible!
🔑 Key Takeaway
A closure is when a function "closes over" the variables from its surrounding scope — and keeps access to them even after the outer function is gone.
Mastering closures = leveling up your JavaScript skills 🔥
Subscribe to my newsletter
Read articles from Noura Mostafa directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Noura Mostafa
Noura Mostafa
🚀 Aspiring Full-Stack Developer Blogger 👨💻 Passionate about web development and coding. ✍️ Sharing my journey through tech via CodeOdyssey 🌍 "The code is a journey, not a destination."