JavaScript Closures Deep Dive: Complete Guide

Understand JavaScript closures from the ground up. Learn how closures capture variables, why they matter, and how to use them for data privacy, factories, and event handlers.

JavaScriptintermediate
12 min read

A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished executing. Closures are one of the most powerful and commonly misunderstood features in JavaScript. They power data privacy, callback functions, event handlers, module patterns, and most of the patterns you see in modern JavaScript frameworks. This guide explains closures from first principles with clear examples.

What Is a Closure?

A closure is created every time a function is defined inside another function and the inner function references variables from the outer function:

javascriptjavascript
function createGreeting(greeting) {
  // greeting is a variable in the outer function's scope
 
  function greet(name) {
    // This inner function "closes over" greeting
    return `${greeting}, ${name}!`;
  }
 
  return greet; // Return the inner function
}
 
const sayHello = createGreeting("Hello");
const sayHi = createGreeting("Hi");
 
console.log(sayHello("Alice")); // "Hello, Alice!"
console.log(sayHi("Bob"));     // "Hi, Bob!"
console.log(sayHello("Charlie")); // "Hello, Charlie!"

After createGreeting("Hello") finishes, you might expect the greeting variable to be gone. But greet holds a reference to it. That reference, that "memory" of the outer scope, is the closure.

Breaking It Down

javascriptjavascript
function outer() {
  let count = 0; // This variable lives in outer's scope
 
  function inner() {
    count++; // inner "closes over" count
    console.log(count);
  }
 
  return inner;
}
 
const counter = outer(); // outer runs and returns inner
// outer() is done, but count is NOT garbage collected
 
counter(); // 1 - count persists!
counter(); // 2 - same count variable
counter(); // 3 - still the same count
 
const counter2 = outer(); // A NEW closure with its own count
counter2(); // 1 - fresh count, separate from counter's count

How Closures Work Under the Hood

When JavaScript creates a function, it attaches a hidden [[Environment]] reference that points to the lexical scope where the function was defined. This is what makes closures work:

StepWhat Happens
1. Call outer()A new execution context is created with count = 0
2. Define inner()inner stores a reference to outer's scope (its [[Environment]])
3. Return innerouter's execution context is popped from the call stack
4. Call counter()inner executes and follows its [[Environment]] to find count
5. count++The original count variable is updated (not a copy)

The critical insight: closures capture the variable itself, not its value at the time. This means they always read the current value:

javascriptjavascript
function createTimer() {
  let seconds = 0;
 
  return {
    tick() { seconds++; },
    getTime() { return seconds; } // Always reads the CURRENT value
  };
}
 
const timer = createTimer();
timer.tick();
timer.tick();
timer.tick();
console.log(timer.getTime()); // 3 (not 0)

Closures for Data Privacy

JavaScript has no built-in private keyword for variables. Closures provide true data privacy by hiding variables inside a function scope:

javascriptjavascript
function createBankAccount(initialBalance) {
  let balance = initialBalance; // Private! Not accessible from outside
  const transactions = [];      // Private!
 
  function logTransaction(type, amount) {
    transactions.push({
      type,
      amount,
      balance,
      timestamp: new Date().toISOString()
    });
  }
 
  return {
    deposit(amount) {
      if (amount <= 0) throw new Error("Deposit must be positive");
      balance += amount;
      logTransaction("deposit", amount);
      return balance;
    },
 
    withdraw(amount) {
      if (amount <= 0) throw new Error("Withdrawal must be positive");
      if (amount > balance) throw new Error("Insufficient funds");
      balance -= amount;
      logTransaction("withdrawal", amount);
      return balance;
    },
 
    getBalance() {
      return balance;
    },
 
    getHistory() {
      return [...transactions]; // Return a copy, not the original
    }
  };
}
 
const account = createBankAccount(100);
account.deposit(50);       // 150
account.withdraw(30);      // 120
console.log(account.getBalance()); // 120
 
// Cannot access balance or transactions directly
console.log(account.balance);       // undefined
console.log(account.transactions);  // undefined

Private vs Public Comparison

PatternAccessImplemented With
Public propertyAnywhereobject.prop
Private variableOnly inside the closurelet inside outer function
Privileged methodPublic method that reads private dataReturned object method

Closures as Function Factories

A factory function returns a new function configured by its arguments. Each returned function carries its own closure:

javascriptjavascript
function createMultiplier(factor) {
  return function (number) {
    return number * factor;
  };
}
 
const double = createMultiplier(2);
const triple = createMultiplier(3);
const toPercent = createMultiplier(100);
 
console.log(double(5));     // 10
console.log(triple(5));     // 15
console.log(toPercent(0.75)); // 75

Configurable Validators

javascriptjavascript
function createValidator(rules) {
  return function (value) {
    const errors = [];
 
    if (rules.minLength && value.length < rules.minLength) {
      errors.push(`Must be at least ${rules.minLength} characters`);
    }
    if (rules.maxLength && value.length > rules.maxLength) {
      errors.push(`Must be at most ${rules.maxLength} characters`);
    }
    if (rules.pattern && !rules.pattern.test(value)) {
      errors.push(rules.patternMessage || "Invalid format");
    }
 
    return { valid: errors.length === 0, errors };
  };
}
 
const validateEmail = createValidator({
  pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
  patternMessage: "Must be a valid email"
});
 
const validatePassword = createValidator({
  minLength: 8,
  maxLength: 64,
  pattern: /[A-Z]/,
  patternMessage: "Must contain at least one uppercase letter"
});
 
console.log(validateEmail("user@site.com"));  // { valid: true, errors: [] }
console.log(validatePassword("short"));       // { valid: false, errors: [...] }

Configurable Formatters

javascriptjavascript
function createFormatter(locale, options) {
  const formatter = new Intl.NumberFormat(locale, options);
  return function (value) {
    return formatter.format(value);
  };
}
 
const formatUSD = createFormatter("en-US", { style: "currency", currency: "USD" });
const formatEUR = createFormatter("de-DE", { style: "currency", currency: "EUR" });
const formatPercent = createFormatter("en-US", { style: "percent", minimumFractionDigits: 1 });
 
console.log(formatUSD(1234.5));   // "$1,234.50"
console.log(formatEUR(1234.5));   // "1.234,50 €"
console.log(formatPercent(0.856)); // "85.6%"

Closures in Event Handlers

Every event listener that references variables from its enclosing scope is using a closure:

javascriptjavascript
function setupButtons() {
  const buttons = document.querySelectorAll(".action-btn");
 
  buttons.forEach((button, index) => {
    let clickCount = 0; // Each button gets its OWN clickCount
 
    button.addEventListener("click", () => {
      clickCount++;
      button.textContent = `Button ${index + 1}: ${clickCount} clicks`;
    });
  });
}
 
setupButtons();

The Classic Loop Problem

javascriptjavascript
// PROBLEM: All timeouts log 5
for (var i = 0; i < 5; i++) {
  setTimeout(() => {
    console.log(i); // 5, 5, 5, 5, 5
  }, i * 100);
}
// `var` has function scope, so all callbacks share the same `i`
// By the time they run, the loop is done and i === 5

Three Solutions

javascriptjavascript
// Solution 1: Use let (block scope creates a new i each iteration)
for (let i = 0; i < 5; i++) {
  setTimeout(() => {
    console.log(i); // 0, 1, 2, 3, 4
  }, i * 100);
}
 
// Solution 2: IIFE creates a new scope each iteration
for (var i = 0; i < 5; i++) {
  (function (j) {
    setTimeout(() => {
      console.log(j); // 0, 1, 2, 3, 4
    }, j * 100);
  })(i);
}
 
// Solution 3: Closure factory
function createLogger(value) {
  return function () {
    console.log(value);
  };
}
 
for (var i = 0; i < 5; i++) {
  setTimeout(createLogger(i), i * 100); // 0, 1, 2, 3, 4
}

Closures for Memoization

Memoization caches expensive function results using a closure:

javascriptjavascript
function memoize(fn) {
  const cache = new Map(); // Private cache via closure
 
  return function (...args) {
    const key = JSON.stringify(args);
 
    if (cache.has(key)) {
      console.log("Cache hit:", key);
      return cache.get(key);
    }
 
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}
 
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}
 
const fastFib = memoize(function fib(n) {
  if (n <= 1) return n;
  return fastFib(n - 1) + fastFib(n - 2);
});
 
console.log(fastFib(40)); // Instant (cached)
console.log(fastFib(40)); // Cache hit

The Module Pattern

Before ES6 modules, closures were the only way to create modules with private state:

javascriptjavascript
const counterModule = (function () {
  let count = 0; // Private
 
  return {
    increment() { return ++count; },
    decrement() { return --count; },
    getCount() { return count; },
    reset() { count = 0; return count; }
  };
})();
 
counterModule.increment(); // 1
counterModule.increment(); // 2
console.log(counterModule.getCount()); // 2
console.log(counterModule.count); // undefined (private)

This combines an IIFE with closures to create an isolated module.

Closures vs No Closures

Without ClosureWith Closure
Variables are accessible globallyVariables are hidden inside the function
State can be modified by any codeState can only be changed through exposed methods
No encapsulationFull encapsulation
Risk of naming collisionsNames are scoped and private
Testing is harder (global state)Testing is easier (isolated state)

Common Mistakes

Mistake 1: Not Realizing Closures Capture by Reference

javascriptjavascript
function createFunctions() {
  let value = 1;
 
  const getValue = () => value;
  value = 2; // Mutating after the closure is created
 
  return getValue;
}
 
console.log(createFunctions()()); // 2 (not 1!)
// The closure captures the VARIABLE, not the value at creation time

Mistake 2: Unintended Shared State

javascriptjavascript
// BAD: All handlers share the same config reference
function setupHandlers(config) {
  return {
    onClick() { console.log(config.color); },
    onHover() { console.log(config.size); }
  };
}
 
const config = { color: "red", size: 10 };
const handlers = setupHandlers(config);
config.color = "blue"; // Mutating the original object!
handlers.onClick(); // "blue" (not "red")
 
// FIX: Copy the config
function setupHandlersSafe(config) {
  const localConfig = { ...config }; // Snapshot
  return {
    onClick() { console.log(localConfig.color); },
    onHover() { console.log(localConfig.size); }
  };
}
Rune AI

Rune AI

Key Insights

  • Closures capture variables, not values: The inner function holds a reference to the outer variable, meaning it always reads the current value
  • Data privacy without classes: Closures provide true encapsulation by hiding variables inside a function scope with only exposed methods for access
  • Function factories use closures: Returning configured functions (multipliers, validators, formatters) from a factory is a core closure pattern
  • The classic loop fix is let: Using let instead of var in loops creates a new binding per iteration, giving each closure its own copy
  • Watch for memory leaks: Closures prevent garbage collection of captured variables, so clean up event listeners and avoid closing over large objects unnecessarily
RunePowered by Rune AI

Frequently Asked Questions

What exactly is a closure in JavaScript?

closure is a function combined with a reference to the variables in the scope where it was defined. When a function is created inside another function and uses variables from the outer function, it "closes over" those variables. Even after the outer function finishes, the inner function retains access to those variables through the closure. Every function in JavaScript creates a closure, but we typically use the term when the inner function outlives the outer function.

Do closures copy the variable or reference it?

Closures capture by reference, not by value. The closed-over function sees the current state of the variable, not a snapshot from when the closure was created. If the variable changes after the closure is defined, the closure will read the updated value. This is why the classic `var` loop problem produces unexpected results, because all closures reference the same variable.

How are closures different from global variables?

Global variables are accessible from anywhere in the code, making them prone to accidental modification and naming collisions. Closures encapsulate variables inside a [function scope](/tutorials/programming-languages/javascript/javascript-function-scope-local-vs-global-scope) where only the returned functions can access them. This provides data privacy, prevents external mutation, and avoids polluting the global namespace.

When should I use closures in real applications?

Use closures for data privacy (hiding implementation details behind a public API), function factories (creating configured functions like validators or formatters), memoization (caching expensive computation results), [event handlers](/tutorials/programming-languages/javascript/how-to-add-event-listeners-in-js-complete-guide) that need to remember per-element state, and [callback functions](/tutorials/programming-languages/javascript/what-is-a-callback-function-in-js-full-tutorial) that need access to the surrounding context.

Can closures cause memory leaks?

Yes, if closures hold references to large objects that are no longer needed, the garbage collector cannot free that memory. This happens most often with [event listeners](/tutorials/programming-languages/javascript/how-to-add-event-listeners-in-js-complete-guide) attached to DOM elements that get removed without removing the listener. Always remove event listeners when the element is destroyed, and avoid closing over large data structures unnecessarily.

Conclusion

Closures happen whenever a function retains access to variables from the scope where it was created. They are the foundation of data privacy, function factories, memoization, the module pattern, and virtually every callback and event handler in JavaScript. The key rule to remember: closures capture variables by reference, not by value, so they always see the current state of the captured variable.