Set your Publisher ID in src/config/ads.ts to display live ads.
Scope, Closures & The Temporal Dead Zone
Lexical scope, closure memory encapsulation, and var vs let/const hoisting
Closures are a fundamental JavaScript concept where an inner function retains access to its enclosing outer lexical scope even after the outer function has finished executing.
Understanding Lexical Scope and Closures
Lexical Scope: Variable resolution is determined strictly by the physical location of code nesting in the source file.
Closure Definition: A function bundled together with references to its surrounding lexical state.
Data Privacy / Encapsulation: Closures allow creating private variables that cannot be accessed or modified from the outside world.
Hoisting & TDZ: var declarations are hoisted and initialized to undefined. let and const are hoisted into the Temporal Dead Zone (TDZ), throwing a ReferenceError if accessed before declaration.
function createBankAccount(initialBalance) {
// Private variable encapsulated by closure
let balance = initialBalance;
return {
deposit(amount) {
if (amount > 0) balance += amount;
return balance;
},
withdraw(amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return balance;
}
return "Insufficient funds";
},
getBalance() {
return balance;
}
};
}
const account = createBankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
// account.balance is undefined! Private to the closure!Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
What is a closure in JavaScript?