A closure is created in JavaScript when a function remembers and accesses variables from its outer scope, even after that outer function has finished executing.
Closures let inner functions keep using variables that would normally be out of scope.
🧾 Example of a Closure:
function outer() {
let message = "Hello from closure!";
function inner() {
console.log(message);
}
return inner;
}
const greet = outer();
greet(); // ✅ "Hello from closure!"
Here, inner() still has access to message even though outer() has already returned — that’s a closure in action.
🔒 Using Closures for Private Variables:
Closures are often used to protect data from being directly modified.
function createCounter() {
let count = 0; // private variable
return {
increment: function () {
count++;
console.log(count);
},
decrement: function () {
count--;
console.log(count);
},
getValue: function () {
return count;
}
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
console.log(counter.getValue()); // 2
👉 Here, count can’t be accessed directly — only through the methods returned.
✅ Why use closures:
- To encapsulate data.
- To avoid polluting the global scope.
- To create private variables and functions that aren’t directly accessible from outside.