JavaScript:JavaScript Closures and Scope: Lexical Scoping Guide
JavaScript•Closures & Scope

JavaScript Closures and Scope: Lexical Scoping Guide

A closure is the combination of a function bundled together with references to its surrounding lexical environment.

Syntax

function createCounter() { let count = 0; return () => ++count; }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
ClosureConceptRetains access to enclosing variables even after outer function returns.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// JavaScript Closures: Private Counter Factory
function createWallet(initialBalance) {
  let balance = initialBalance; // Private variable encapsulated by closure

  return {
    deposit(amount) {
      if (amount > 0) balance += amount;
      return balance;
    },
    withdraw(amount) {
      if (amount > 0 && amount <= balance) {
        balance -= amount;
        return true;
      }
      return false;
    },
    getBalance() {
      return balance;
    }
  };
}

const myWallet = createWallet(100);
myWallet.deposit(50);
myWallet.withdraw(30);
console.log("Current Wallet Balance: $" + myWallet.getBalance());
Expected Output:
Current Wallet Balance: $120

How It Works: Step-by-Step

  • Lines 2-3: balance is encapsulated within createWallet and cannot be accessed from outside.
  • Lines 5-18: Returned object methods maintain access to balance via closure.

Key Concepts

  • Closures provide data privacy and encapsulation without needing classes.
  • Variables closed over persist in memory as long as the inner functions exist.
  • Used extensively in event listeners, callbacks, and functional programming factories.

Common Mistake: Creating closures inside loops with var instead of let

var is function-scoped; all callbacks share the single mutated variable. let creates a fresh binding per iteration.

❌ Incorrect
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 10); } // Prints 3, 3, 3!
✅ Correct
for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 10); } // Prints 0, 1, 2

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler