JavaScript Closures: Lexical Scoping, Encapsulation & Memory Lifecycle
Master closures in JavaScript: lexical scope, function factories, data encapsulation, private variables, and memory management.
function createBankAccount(initialBalance) {
let balance = initialBalance; // Private state protected by closure
return {
deposit(amount) {
if (amount > 0) balance += amount;
return balance;
},
withdraw(amount) {
if (amount > 0 && amount <= balance) balance -= amount;
return balance;
},
getBalance() {
return balance;
}
};
}
const account = createBankAccount(5000);
account.deposit(2500);
console.log("Balance:", account.getBalance()); // 7500
// balance variable is inaccessible directly from global scope!
1. What is a Closure?
A closure is the combination of a function bundled together with references to its surrounding lexical environment. In JavaScript, closures are created every time a function is created at function creation time.
2. Data Encapsulation & Private Variables
Before ES2022 private class fields (#field), closures were the primary mechanism for implementing data hiding and private variables in JavaScript software design.
- A closure retains access to outer variables even after the outer function has returned.
- Closures enable module patterns, currying, and memoization techniques.
- Beware of unintentionally retaining large objects in closures, which can lead to memory retention.
Frequently Asked Questions
Do closures consume more memory?
Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.
Explore Related Course Call 7503962162