Table of Contents

Introduction

JavaScript closures is created when a function remembers and can access variables from its outer lexical scope, even after the outer function has finished executing. Closures allow inner functions to preserve access to data, create private state, build reusable function factories, and manage callbacks. They are a fundamental part of JavaScript’s lexical scoping.

How JavaScript Closures Work

JavaScript uses lexical scoping, which means a function’s access to variables is determined by where the function is written. A nested function can access variables in its own scope and in enclosing scopes. When that nested function is returned or passed elsewhere, it retains access to the lexical environment in which it was created.

function outerFunction() {
  const message = "Hello from the outer function";
  function innerFunction() {
    console.log(message);
  }
  innerFunction();
}
outerFunction(); // Hello from the outer function

The inner function can read message because it is defined inside the function where that variable is declared.

Returning an Inner Function

A closure becomes especially useful when an outer function returns an inner function. The outer function can finish executing, but the returned function can still access its surrounding bindings.

function createMessage() {
  const message = "JavaScript closures are useful";
  return function() {
    console.log(message);
  };
}
const showMessage = createMessage();
showMessage(); // JavaScript closures are useful

The returned function keeps access to message after createMessage() has returned. A closure retains access to variable bindings rather than taking a one-time snapshot of their values.

Closures Preserve Access to Updated Variables

A closure can read and update variables from its outer environment. Multiple calls to the returned function can work with the same binding.

function createCounter() {
  let count = 0;
  return function() {
    count++;
    console.log(count);
  };
}
const counter = createCounter();
counter(); // 1
counter(); // 2
counter(); // 3

The count variable is created once when createCounter() runs. The returned function increments that same variable on every call.

Creating Private Variables with Closures

Closures can keep data private by placing variables inside an outer function and exposing selected operations through returned methods. Code outside the function cannot directly access the local binding.

function createBankAccount(initialBalance) {
  let balance = initialBalance;
  return {
    deposit(amount) {
      if (amount > 0) balance += amount;
      return balance;
    },
    withdraw(amount) {
      if (amount > 0 && amount <= balance) balance -= amount;
      return balance;
    },
    getBalance() {
      return balance;
    }
  };
}
const account = createBankAccount(1000);
console.log(account.getBalance()); // 1000
console.log(account.deposit(500)); // 1500
console.log(account.withdraw(200)); // 1300

The balance variable is not a property of the returned object. The methods close over the same variable and provide controlled access to it.

Using Closures to Create Function Factories

A function factory creates and returns another function. The returned function can remember configuration values supplied when it was created.

function multiplyBy(multiplier) {
  return function(number) {
    return number * multiplier;
  };
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15

The double function remembers 2, while triple remembers 3. Each call to multiplyBy() creates a separate lexical environment.

JavaScript Closures in Callback Functions

Callbacks often execute after the code that created them has finished. A callback can still access variables from its original scope because it retains its lexical environment.

function createGreeting(name) {
  return function() {
    console.log("Welcome, " + name);
  };
}
const greetUser = createGreeting("Nadia");
setTimeout(greetUser, 1000); // Welcome, Nadia

The callback remembers the name parameter and uses it when the timer invokes the function later.

Closures with Event Listeners

An event handler can use a closure to remember information that was available when the listener was registered.

function attachMessage(button, message) {
  button.addEventListener("click", function() {
    console.log(message);
  });
}
const button = document.querySelector("#saveButton");
attachMessage(button, "Your changes have been saved.");

The handler closes over the message parameter. When the user clicks the button, the callback can still read that value.

Closures Inside Loops

Closures inside loops can behave unexpectedly when callbacks share a variable declared with var. Since var is function-scoped, callbacks created in the loop can all refer to the same binding.

for (var i = 1; i <= 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 100);
}
// Output: 4, 4, 4

When the callbacks execute, the loop has completed and the shared i value is 4. Using let creates a new block-scoped binding for each iteration:

for (let i = 1; i <= 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 100);
}
// Output: 1, 2, 3

Each callback captures the binding for its own iteration. This is usually the clearest solution in modern JavaScript.

Closures with Multiple Nested Functions

An inner function can access variables from multiple enclosing scopes. JavaScript searches the scope chain from the current function outward until it finds the referenced binding.

const application = "Learning App";
function userSection() {
  const user = "Rahim";
  function showDetails() {
    const role = "Developer";
    console.log(application, user, role);
  }
  return showDetails;
}
const displayDetails = userSection();
displayDetails(); // Learning App Rahim Developer

The innermost function accesses its local role, the enclosing user, and the outer application variable. Its lexical access remains available after userSection() returns.

Closures and Lexical Scope

Lexical scope determines which variables a function can access based on where the function is defined. A closure relies on this rule. Moving a function to another variable or passing it to another part of a program does not change the scope in which it was created.

const language = "JavaScript";
function createPrinter() {
  const topic = "Closures";
  return function() {
    console.log(language + " " + topic);
  };
}
const printer = createPrinter();
printer(); // JavaScript Closures

The returned function continues to use the lexical environment of createPrinter(), regardless of where it is later called.

Maintaining Independent State with Closures

Each call to an outer function creates a new execution context and its own local bindings. Returned functions keep access to the bindings from their respective calls, making closures useful for independent stateful utilities.

function createScore(initialScore) {
  let score = initialScore;
  return {
    increase() { return ++score; },
    decrease() { return --score; },
    current() { return score; }
  };
}
const playerOne = createScore(10);
const playerTwo = createScore(20);
console.log(playerOne.increase()); // 11
console.log(playerTwo.decrease()); // 19
console.log(playerOne.current()); // 11
console.log(playerTwo.current()); // 19

The two score objects use separate lexical environments. Updating one score does not affect the other.

Closures and JavaScript Modules

Closures can implement a module-like pattern by keeping internal data private and returning a public interface. Modern JavaScript also provides native modules with import and export, but the closure pattern remains useful for understanding encapsulation.

const shoppingCart = (function() {
  const items = [];
  return {
    add(item) { items.push(item); },
    getItems() { return [...items]; },
    getCount() { return items.length; }
  };
})();
shoppingCart.add("Book");
shoppingCart.add("Pen");
console.log(shoppingCart.getCount()); // 2
console.log(shoppingCart.getItems()); // ["Book", "Pen"]

The items array is accessible through the returned methods, but it is not exposed as a public property. The getter returns a copy rather than the original array.

Closures and Memory Management

A closure keeps access to the lexical bindings it needs while the function remains reachable. This can keep referenced data in memory longer than expected. For example, an event listener attached to a long-lived element can retain variables used by its callback.

function registerHandler(button) {
  const message = "Action completed";
  function handleClick() {
    console.log(message);
  }
  button.addEventListener("click", handleClick);
  return function cleanup() {
    button.removeEventListener("click", handleClick);
  };
}
const cleanupHandler = registerHandler(
  document.querySelector("#actionButton")
);
// Call cleanupHandler() when the listener is no longer needed.

The cleanup function closes over the button and handler references. Calling it removes the event listener. JavaScript’s garbage collector manages memory automatically, but unnecessary references can prevent objects from becoming eligible for collection.

Closures with Asynchronous JavaScript

Asynchronous callbacks often run after their surrounding function has completed. Closures let those callbacks retain the values they need without relying on global variables.

function loadUserMessage(userName) {
  const prefix = "Hello";
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(prefix + ", " + userName + "!");
    }, 500);
  });
}
loadUserMessage("Sadia").then((message) => {
  console.log(message); // Hello, Sadia!
});

The timer callback closes over prefix and userName. It can use both values later when it resolves the promise.