Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 156 ยท Functions

Closures

Understand JavaScript closures with clear examples - counters, private state, function factories, once() helpers and the classic var-in-a-loop bug.

A closure is a function together with the variables it could see when it was created. In JavaScript, every function keeps a link to the scope it was written in, and it keeps that link for as long as the function exists โ€” even after the outer function has finished running. That one fact powers a surprising amount of everyday code: counters, private data, configuration helpers, event handlers and most callbacks.

Closures often sound mysterious, but you have already been using them. Any time a function reads a variable from outside its own body, it is closing over that variable. This lesson makes the behavior visible, shows the patterns that rely on it, and explains the famous loop bug that trips up almost everyone once.

A function that remembers

In Scope and Hoisting you saw that an inner function can read the variables of the function around it. The interesting part is what happens when the inner function outlives the outer one:

JS A closure in its simplest form

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When makeGreeter("Hello") returns, you might expect greeting and punctuation to disappear. They don't. The returned function still refers to them, so JavaScript keeps them alive. Each call to makeGreeter creates a fresh scope, which is why hello and hola remember different greetings.

Closures capture variables, not values

A closure doesn't take a snapshot. It holds a live connection to the variable itself. If the variable changes later, the closure sees the new value, and if the closure changes it, everyone else sharing that variable sees the change too.

JS Live variables, not copies

Press Run (or Ctrl + Enter) to see the console output here.

No output.

clicks and views each have their own count, because each call to makeCounter() ran the function body again and created a new variable. Calling one counter never affects the other.

Private state

JavaScript objects are open: anyone can read or overwrite a property. Closures give you a way to hide data. Variables inside a function are unreachable from outside, except through the functions you choose to return:

JS A wallet with private state

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The only way to change balance is through deposit() and spend(), which validate their input. Code outside the wallet can't set the balance to a nonsense value by accident. Classes now offer a dedicated syntax for this, private fields like #balance, but the closure pattern is still common and works everywhere.

Function factories

A function that builds and returns other functions is often called a factory. Closures let each produced function carry its own configuration:

JavaScript
function makeFormatter(currency, decimals) {
  return (amount) => `${amount.toFixed(decimals)} ${currency}`;
}

const euros = makeFormatter("EUR", 2);
const yen = makeFormatter("JPY", 0);

euros(9.5);  // "9.50 EUR"
yen(1234.6); // "1235 JPY"

You configure once, then call the result many times without repeating the settings. You'll see this idea again in Higher-Order Functions.

A once() helper

Closures can also remember whether something has happened. This helper wraps any function so that it runs only the first time:

JS once(): run a function a single time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The message prints once; every later call just returns the saved result. done and result are private to that one wrapped function.

The loop pitfall

Here is the bug that made closures famous. Suppose you create several functions in a loop, each meant to remember its own loop number:

JS var vs let in a loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With var, all three functions print 4. There is only one i for the whole function (remember, var ignores blocks), and all three closures share it. By the time you call them, the loop has finished and i is 4.

With let, a for loop creates a new binding of j for every iteration, so each closure captures its own variable holding 1, 2 or 3. That special per-iteration behavior is one of the main reasons let was added to the language.

The same bug shows up with timers and event handlers, which run later:

JavaScript
for (var n = 1; n <= 3; n++) {
  setTimeout(() => console.log(n), 100); // 4, 4, 4
}

for (let n = 1; n <= 3; n++) {
  setTimeout(() => console.log(n), 100); // 1, 2, 3
}

In old code written before let, you may see this fixed with an immediately invoked function that creates a new scope per iteration: (function (k) { โ€ฆ })(i). Today, using let is the fix.

Closures you already write

Closures aren't only for clever patterns. Every event handler or timer callback that uses a variable from the surrounding code is one:

JavaScript
function setupLikeButton(button, postTitle) {
  let likes = 0;

  button.addEventListener("click", () => {
    likes++;
    button.textContent = `โ™ฅ ${likes} โ€” ${postTitle}`;
  });
}

setupLikeButton() returns right away, long before anyone clicks. When a click finally happens, the arrow function still has likes, button and postTitle available, because it closed over them. Call setupLikeButton() for ten buttons and each one gets its own private likes count, with no global variables and no extra bookkeeping. This is the same idea as the counter factory, just triggered by a click instead of a function call.

Closures and memory

Because a closure keeps its variables alive, those variables can't be garbage collected while the closure is reachable. Usually this is exactly what you want. It becomes a problem only when a long-lived closure, such as an event listener on document or a timer that never stops, holds on to something large, such as a big array or a DOM element that was removed from the page.

Clean up long-lived closures. Remove event listeners you no longer need with removeEventListener(), stop intervals with clearInterval(), and avoid capturing big data in a callback when it only needs a small piece of it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a closure?

    Every function keeps a link to the scope it was written in. That combination of function and remembered variables is a closure.
  2. 2. Given const a = makeCounter(); const b = makeCounter(); where each call creates let count = 0 and returns a function that increments it, what does a(); a(); b(); return from the final call?

    Each call to makeCounter() creates its own count. b has never been called before, so its counter goes from 0 to 1.
  3. 3. A loop for (var i = 0; i < 3; i++) fns.push(() => i); runs. What do the three functions return?

    There is a single function-scoped i, shared by all three closures. After the loop it holds 3.
  4. 4. Do closures copy the value of a variable at the moment they are created?

    Closures see later changes to the variable, and changes they make are visible to other code sharing it.
  5. 5. Why can closures cause memory to stay in use?

    As long as the closure can still be called, the variables it captured must stay alive. Remove listeners and timers you no longer need.

Summary

  • A closure is a function plus the variables it could see where it was written; those variables live as long as the function does.
  • Closures capture live variables, not snapshots, and each call of the outer function creates a fresh set.
  • Closures give you private state: expose functions that control access, keep the data itself hidden.
  • Factories and helpers such as once() use closures to remember configuration or history.
  • In loops, let creates a new binding per iteration; var shares one variable, which causes the classic "all 3s" bug.

Next: Higher-Order Functions and Callbacks โ€” passing functions around like any other value.