ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

JavaScript Tutorial• 7 min read

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.

Private State Encapsulation with Closures
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!
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is a closure in JavaScript?