Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk5 min

JavaScript Closures Explained: How Functions Remember Their Scope

A JavaScript closure lets a function keep access to its defining scope. See how it works with returned functions, counters, factories, callbacks, and loop variables.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A JavaScript closure lets a function keep using variables from the scope where it was created, even when it runs later or somewhere else. That is why a callback can still access the values around it, and why a function returned from another function can maintain private state. The examples below use JavaScript; other languages use the term “closure” with their own syntax and rules.

What is a closure?

A closure is a function together with access to its surrounding lexical environment—the variables and other bindings available where the function was defined. “Lexical” means that the code’s written location determines which surrounding names it can use, not the place from which the function is later called.

As an Amazon Associate I earn from qualifying purchases.

Start with a nested function:

function greet() {
  const message = "Hello from the outer function";

  function sayHello() {
    console.log(message);
  }

  sayHello();
}

greet();

sayHello can read message because it was defined inside greet. The inner function’s scope is nested within the outer function’s scope. MDN describes a JavaScript closure as a function bundled with references to its surrounding state (MDN: Closures; MDN: Closure glossary).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How can a function use a variable after its creator has finished?

Return the inner function instead of calling it immediately:

function makeGreeter() {
  const message = "Hello from the outer function";

  return function sayHello() {
    console.log(message);
  };
}

const greetLater = makeGreeter();
greetLater(); // Hello from the outer function

makeGreeter() has finished by the time greetLater() runs. But the returned function retains access to the message binding in the environment where it was created. The function does not need to be called inside makeGreeter to use that name.

This is the key idea: the function carries access to its defining context with it. A closure is not a special declaration or keyword; it is the function-and-environment relationship that results from lexical scoping.

What does a closure retain: a value or a changing variable?

In JavaScript, it is useful to think of a closure as retaining access to a binding—a named place whose associated value can change—rather than assuming it takes a frozen snapshot when the function is created.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function makeCounter() {
  let count = 0;

  return function increment() {
    count += 1;
    return count;
  };
}

const nextCount = makeCounter();
console.log(nextCount()); // 1
console.log(nextCount()); // 2

The returned increment function can both read and update count. Its calls share the same binding, so the next call starts with the result of the previous one. Calling makeCounter() again creates a separate environment and a separate count.

This is why “closures capture values” can be misleading if it suggests that every captured value is copied once and never changes. What a closure can capture, and how captured state behaves, depends on the language and its rules.

Where are closures useful?

Creating specialized functions

A function factory returns a function configured with information from the factory call. For example, this adder creates functions that each remember a different number:

function makeAdder(x) {
  return function addTo(y) {
    return x + y;
  };
}

const addFive = makeAdder(5);
const addTen = makeAdder(10);

console.log(addFive(3)); // 8
console.log(addTen(3));  // 13

addFive and addTen use the same function code, but each closes over the x binding created by a different call to makeAdder.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keeping state behind a small interface

A closure can keep a variable out of the caller’s direct reach while exposing functions that operate on it. For instance, a counter can return both an increment function and a read function that share one private binding:

function createCounter() {
  let count = 0;

  return {
    increment() {
      count += 1;
      return count;
    },
    current() {
      return count;
    }
  };
}

const counter = createCounter();
counter.increment();
console.log(counter.current()); // 1

The returned methods share access to count; code using the returned object has no direct name with which to change that variable. This is one way to organize state, not a rule that closures replace objects or are always the best design.

Remembering context in callbacks

A callback is a function passed to other code to be called later. A closure lets that callback use names from its defining scope when it eventually runs—for example, after an event or another operation. This is the same mechanism shown by greetLater: the delay between creation and invocation does not by itself remove access to the surrounding binding.

Why can callbacks in a JavaScript loop show the wrong value?

A common pitfall involves callbacks created in a loop with var. Because var is function-scoped rather than block-scoped, the callbacks in this example share one i binding:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const callbacks = [];

for (var i = 0; i < 3; i++) {
  callbacks.push(function () {
    console.log(i);
  });
}

callbacks.forEach(callback => callback()); // 3, 3, 3

Each callback closes over the same binding. The loop finishes and changes i to 3 before the callbacks are invoked, so all three read that current value. The callbacks have not each captured a separate number.

For this pattern, use let in the loop declaration. It creates a block-scoped binding for each iteration, so each callback can use the iteration’s value:

const callbacks = [];

for (let i = 0; i < 3; i++) {
  callbacks.push(function () {
    console.log(i);
  });
}

callbacks.forEach(callback => callback()); // 0, 1, 2

The distinction is about JavaScript scope and the bindings the callbacks share; it is not evidence that closures always capture the final value. MDN discusses this loop behavior and the use of block-scoped declarations in its JavaScript closures guide.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Does “closure” mean the same thing in every language?

The broad idea—functions retaining access to context from where they are defined—appears in multiple languages, but syntax and capture rules differ. Swift’s language guide describes closures as self-contained blocks that can be passed around, and notes that they can capture constants and variables from their defining context. It also treats global functions, nested functions, and closure expressions as forms of closures (Swift language guide: Closures).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

That comparison is a reminder to keep examples language-specific. JavaScript’s var, let, and lexical-scope behavior should not be assumed to describe every language’s closures.

How to recognize a closure in your own code

  • Find a function that uses a name not declared inside that function.
  • Locate where that name is declared in an enclosing scope.
  • Check whether the function can be called after the enclosing function returns, or from a callback invoked later.
  • If the name can change, identify which calls share its binding and which factory calls create separate environments.

If those pieces line up, the function is using a closure. Once you identify the enclosing binding, behavior that may have seemed mysterious—such as a counter persisting between calls or several callbacks seeing one loop variable—becomes a question of scope, lifetime, and whether the binding is shared.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.