Master closures, how inner functions retain persistent access to outer variables even after the parent function completes.
Average 5.0 by 1 learner
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
A closure is created when an inner function retains access to variables from its outer lexical scope, even AFTER the outer function has finished executing and returned!
Closures power data privacy, private variables, event handlers, factory functions, and stateful hooks in modern JavaScript frameworks like React.
When an outer function returns an inner function, the inner function carries a reference to its outer lexical scope in a persistent memory closure:
function createCounter() {
let count = 0; // Private state variable
return function() {
count = count + 1;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Notice how count remains accessible and remembers its updated state across calls, even though createCounter() finished executing long ago!
[ Execution Context ] -> createCounter() finished & popped off Call Stack
|
v
[ Closure Scope ] -------> count = 3 (Persisted in heap memory!)
^
|
[ Returned Function ] -> counter() reads & updates 'count'
function createBankAccount(initialBalance) {
let balance = initialBalance; // Fully private variable!
return {
deposit(amount) {
balance += amount;
return balance;
},
getBalance() {
return balance;
},
};
}
const account = createBankAccount(100);
console.log(account.deposit(50)); // 150
console.log(account.balance); // undefined (Cannot access private state directly!)
var loop captures the final loop value. Use let in loops so each iteration creates a fresh closure environment!Closures give functions durable state memory. Next, let's transition to Phase 3 and master Arrays and Objects!