Javascript Closure
By Saket Bhatnagar••Beginner to Intermediate
Closure
- 1A closure is a memory block that stores the state (variables) and behavior (functions) of a parent function, so that a child function can access them even after the parent function has finished executing.
- 2Closures are created automatically when a function is defined inside another function and references variables from the outer (parent) function.
- 3They allow the inner function to access the parent function variables even after the parent function has finished executing.
- 4Closures are powerful for preserving data without using global variables or classes (because class are function in javascript).
- 5Each time the outer function is called, a new closure (memory scope) is created.
- 6The child function keeps a reference to the outer function’s variables — not a copy — so the values remain live and can be updated.
- 7Real-life analogy: Imagine a parent owns a plot of land (variables and logic). When the parent gives parts of the land to their children (functions), each child carries their portion and the tools (behavior) needed to manage it. Even if the parent is no longer around, the child still owns and works their land. This is how closures preserve data and behavior.
- 8Another example: Think of a bank account as a closure — it holds a private balance and provides deposit, withdraw, and checkBalance functions. Each account holds its own state and cannot affect other accounts.
- 9Example:
Closure Example: Bank Account
1function createBankAccount(initialBalance) {2 let balance = initialBalance;34 return {5 deposit: function(amount) {6 balance += amount;7 return `Deposited ${amount}. New balance: ${balance}`;8 },9 withdraw: function(amount) {10 if (amount > balance) {11 return "Insufficient funds!";12 }13 balance -= amount;14 return `Withdrew ${amount}. New balance: ${balance}`;15 },16 checkBalance: function() {17 return `Current balance: ${balance}`;18 }19 };20 }2122 const account1 = createBankAccount(1000);23 const account2 = createBankAccount(500);2425 console.log(account1.deposit(200)); // Deposited 200. New balance: 120026 console.log(account2.withdraw(100)); // Withdrew 100. New balance: 40027 console.log(account1.checkBalance()); // 120028 console.log(account2.checkBalance()); // 400💡Note
Note: Each call tocreateBankAccount
creates a new closure with its ownbalance
. The state is preserved separately. - 10Explanation: Even though the outer function
createBankAccount
has finished executing, the returned inner functions have reference of closures stored in memory and use thebalance
variable. Separate closure is created for each call tocreateBankAccount
and it is stored in memory. This is how data privacy is maintained. - 11Advantage: Closures provide private, persistent memory for functions. They're useful in building encapsulated modules, counter functions, factory functions, and callback handlers.
- 12Disadvantage: Closures can lead to memory leaks if variables are retained unnecessarily (e.g., inside unused callbacks or event listeners).