A closure is created when a function remembers and accesses variables from its outer scope, even after that outer function has finished executing.
In simple terms — a closure allows a function to "remember" the environment in which it was created.
1️⃣ Basic Example
function outer() {
let count = 0; // outer variable
function inner() {
count++; // inner function can access outer variable
console.log(count);
}
return inner;
}
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3
✅ The variable count is preserved between calls because inner() closes over the variable from its parent scope — this is a closure.
2️⃣ Practical Example — Private Variables
Closures are often used to create private state in JavaScript.
function createBankAccount() {
let balance = 1000; // private variable
return {
deposit(amount) {
balance += amount;
console.log(`Deposited: ${amount}, New Balance: ${balance}`);
},
withdraw(amount) {
if (amount <= balance) {
balance -= amount;
console.log(`Withdrew: ${amount}, Remaining Balance: ${balance}`);
} else {
console.log("Insufficient funds!");
}
},
};
}
const account = createBankAccount();
account.deposit(500); // Deposited: 500, New Balance: 1500
account.withdraw(200); // Withdrew: 200, Remaining Balance: 1300
console.log(account.balance); // ❌ undefined (balance is private)
✅ Here, balance is hidden and accessible only via the returned methods — demonstrating data encapsulation using closures.
💡 In Short:
A closure is a function that remembers variables from its outer scope even after the outer function has executed — useful for state preservation, data privacy, and callbacks.