JavaScript Closures Explained with Real Code Examples

A closure is a function that remembers the variables around it, even after the outer function has finished running. JavaScript closures explained in one line sounds simple, but the idea only clicks when you see it hold real state: a counter that keeps counting, a private variable no other code can touch, a callback that still knows which item it belongs to. This guide builds that picture with code you can run, then shows where closures help and where they trip people up.

Every function in JavaScript carries a reference to the scope where it was created. That reference is the closure. It is not a special syntax or a library feature. It is how the language works, and once you see it, you will spot it in event handlers, timers, modules, and most of the code you already write.

JavaScript Closures Explained: What a Closure Actually Is

When a function is defined inside another function, the inner function keeps access to the outer function’s variables. The outer function can return, its local variables would normally be gone, but the inner function holds on to them. That held-on scope is the closure. The variables stay alive exactly as long as something can still reach them through the inner function.

Here is the smallest example that shows it:

function makeGreeter(name) {
  return function () {
    return "Hello, " + name;
  };
}

const greetFirdaus = makeGreeter("Firdaus");
console.log(greetFirdaus()); // "Hello, Firdaus"

makeGreeter has finished by the time greetFirdaus runs, yet the returned function still reads name. Nothing else in the program can reach that name. It belongs to the closure, and only the function returned from makeGreeter can use it.

JavaScript Lexical Scope Sets the Rules

JavaScript lexical scope means a function can use variables from the place where it was written, not from the place where it is called. The scope is fixed when you write the code, and the engine works it out by reading outward: the function’s own locals first, then the enclosing function, then the next one out, until it reaches the top level.

That rule explains a common surprise. A function called from somewhere else still reads the variables from its home scope, not from the caller’s scope. Two functions built by the same outer call share the same variables, while two calls to the outer function give each inner function its own separate set. Keep that picture in mind and most closure bugs become easy to trace.

function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

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

counterA and counterB each hold their own count. Calling one never changes the other, because each call to makeCounter builds a fresh scope. That separation is what makes closures useful for state: each instance gets its own private copy.

Closure Real Code Examples You Can Run

The counter above is the classic first example, but closures earn their keep in ordinary application code. The examples below cover the patterns that show up most in real projects, and each one is short enough to paste into a console and try.

A counter with reset

A plain counter only goes up. Add a second function that shares the same scope and you get a small state machine with no global variables at all:

function makeScoreboard() {
  let score = 0;
  return {
    add(points) { score += points; },
    reset() { score = 0; },
    total() { return score; }
  };
}

const board = makeScoreboard();
board.add(10);
board.add(5);
console.log(board.total()); // 15
board.reset();
console.log(board.total()); // 0

All three methods close over the same score. Nothing outside the object can change it except through those methods, which is the whole point: the state has one front door.

Private state without a class

Before private class fields existed, closures were the standard way to hide data in JavaScript. The pattern still works well for small modules, and it reads clearly. A closure real code examples list would be incomplete without it, because it is the pattern behind many small libraries:

function createBankAccount(startingBalance) {
  let balance = startingBalance;
  return {
    deposit(amount) { balance += amount; },
    withdraw(amount) {
      if (amount > balance) return "Not enough funds";
      balance -= amount;
      return balance;
    },
    getBalance() { return balance; }
  };
}

const account = createBankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.balance); // undefined

balance never appears as a property, so outside code cannot read or set it directly. If you build a small REST API with Node.js and Express, this pattern works well for in-memory stores and rate limit counters that should stay out of reach of route handlers.

Callbacks that remember their context

Event handlers and timers run later, long after the code that set them up has moved on. A closure carries the context forward so the callback still knows what it was for:

function setupButton(buttonId, message) {
  const button = document.getElementById(buttonId);
  button.addEventListener("click", function () {
    console.log(message);
  });
}

setupButton("save-btn", "Draft saved");

The handler runs on a click, maybe minutes later, and message is still there. Without closures, every handler would need its data stored on the element or in a global map, and the code would be harder to follow.

Closure Use Cases JavaScript Developers Rely On

Closures show up in a handful of shapes so often that they are worth naming. Data hiding, as in the bank account above, keeps state private without a class. Function factories build small variations of a function from a template, like a greeter per name or a validator per rule. Partial application fixes some arguments now and leaves the rest for later, which cleans up repetitive calls. Debounce and throttle helpers use a closure to hold a timer id between calls. Memoization caches results in a closed-over map so a costly function only runs once per input.

In server code the same shapes appear. Middleware in Express closes over config values, so one factory can produce an auth check per role. A database helper can close over a connection pool and hand out query functions that already know where to connect. When you deploy a Node.js app to a VPS with PM2 and Nginx, none of that changes: closures are a language feature, not a deployment concern, and they behave the same on your laptop and on the server.

The Loop Bug Every Beginner Hits

The most famous closure mistake comes from a loop with var. Because var has function scope, not block scope, every callback made inside the loop closes over the same single variable, and by the time the callbacks run, the loop has finished:

for (var i = 0; i < 3; i++) {
  setTimeout(function () {
    console.log(i);
  }, 100);
}
// prints 3, 3, 3

All three callbacks read the same i, which is 3 when they run. The fix is let, which gives each loop round its own binding:

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

The older fix, wrapping the body in an immediately invoked function, did the same job by creating a new scope per round. You will still see it in old code, and now you know what it was for. If you are containerizing the project that holds this code, this beginner guide to Docker for Node.js apps shows how to ship it without changing how the code itself runs.

When Closures Cause Trouble

Closures keep variables alive, and that is a memory cost. A handler that closes over a large object keeps that object in memory until the handler is removed. On a long-lived page with handlers added and never cleaned up, that adds up. Remove listeners you no longer need, and avoid closing over whole data sets when a single id would do.

Closures can also hide state in a way that makes debugging harder. A bug in a counter built with closures will not show up in any object inspector, because the variable lives in scope, not on an object. When a value looks wrong and you cannot find where it changes, check the functions that share its scope first. A short log inside the closure usually finds the culprit faster than staring at the call stack.

Finally, do not reach for a closure when a plain argument would do. A function that takes its data as parameters is easier to test than one that reads hidden state. Save closures for state that genuinely needs to persist between calls, and pass the rest in as arguments.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.