JavaScript Closures Explained by Building a Private Counter

JavaScript closures let a function keep using the variables from the scope where it was written, even after the outer function has finished running. That sounds odd at first. Once a function returns, you'd expect its local variables to be gone. Yet another function can still remember and update them.

This guide makes that behaviour concrete. You'll build a small counter that keeps its value between calls, and no other code can reach in and change it. Along the way you'll see why it works, how to check that it really is private, and how to fix the closure mistakes that tend to show up in real code.

In short
  • A closure is a function plus the lexical environment it was written in.
  • An outer function holds the state, and a returned inner function is the only way to reach it.
  • The environment stays alive because the stored function can still reach it.
  • Closures capture variables, not snapshots of values, which explains the var loop bug.
  • Use let in loops and release references you no longer need.

Check what you need before you start

The finish line is simple: a counter that goes up by one each time you call it, while its current value stays hidden from the rest of your program. By the end you should be able to explain every line, not just copy it.

You don't need any libraries or setup. Closures are part of the JavaScript language itself, so your browser's developer console or Node.js will both work. What you do need is a little background knowledge, and you probably already have it. The last two items matter most, because closures build directly on how scope works.

  • You're comfortable writing functions
  • You know the difference between let and const
  • You understand how block scope works
  • You understand how function scope works
  • You have a browser console or Node.js open

Write the outer function that holds the state

Start with an ordinary function whose only job is to hold one piece of data. The first line declares a function called createCounter. Inside it, the second line declares count with let and sets it to zero. The closing brace ends the function, which doesn't return anything yet.

Because count is declared inside createCounter, it's a local variable. Code outside the function can't see it or change it. This is plain function scope, and the counter's privacy depends on it.

Use let rather than const. The value of count will change, and a const binding can't be reassigned, so incrementing it later would throw a TypeError. At this point the function isn't useful yet: when createCounter finishes, count looks as though it simply vanishes. The next step changes that.

  • count is declared inside createCounter, not outside it
  • count uses let, because it will be reassigned
  • Nothing is returned yet, and that's expected
function createCounter() {
  let count = 0;
}

Return an inner function that reads and updates count

Now give the outside world a controlled way to use count without exposing it. Keep the first two lines as they are. On the third line, return a new function named increment. Inside it, ++count adds one and returns the new value. Then close the inner function and the outer one.

Notice that increment never declares count. When it needs the variable, JavaScript looks one scope outward, to where the function was written, and finds the count that belongs to createCounter. This is the moment the closure is created.

The inner function changes the real outer variable, not a copy of it, so each call builds on the result of the previous one. Also look carefully at the return line: there are no parentheses after increment. You're returning the function itself, not the result of calling it.

  • increment does not declare its own count
  • ++count updates the outer variable directly
  • The return line has no parentheses after increment
function createCounter() {
  let count = 0;
  return function increment() {
    return ++count;
  };
}

Call createCounter and store the result

With both functions written, put them to use. Open Node.js in your terminal, or your browser console. In Node, type node to start the interactive prompt, then load your counter file. Next, type const counter = createCounter() with parentheses. The prompt prints undefined because a declaration has no value of its own. Typing typeof counter then confirms that it's a function.

Here the parentheses do matter. Running createCounter creates a fresh count, builds increment and returns it, all in one call. Keep that result in a variable. As long as the variable holds the function, the count that belongs to it stays available too.

Each call to createCounter is independent. Call it a second time and you get a separate function with its own count, starting again at zero.

  • createCounter is called with parentheses
  • The returned function is stored in a variable such as counter
  • typeof counter reports 'function'
node

Understand why count survives after the function returns

Back to the opening puzzle: createCounter has returned, so why is count still around? The answer is the lexical environment. Lexical means the scope is fixed by where the code is written, not by where it's called from later.

The function stored in counter holds on to the environment it was created in. Inside that environment is count, which would read two after two calls. Put the two together, a function plus its environment, and you have a closure.

Two details explain the behaviour. First, the link is live: the inner function keeps a reference to the variable itself, so every call sees the latest value. Second, the garbage collector only frees memory that nothing can reach. Your counter variable can still reach that environment, so it stays, and that's what gives you private, lasting state.

  • The closure references count; it doesn't copy it
  • Scope is decided by where the function was written
  • Reachable environments are not garbage collected

Verify the counter counts and stays private

Knowing why it should work is good; proving it is better. Stay in the same Node or console session so your counter is still defined. Call counter() and you'll see 1. Call it again and you'll see 2. The value carries over between calls, which shows the environment really is being kept.

Now try to reach count from outside. Typing counter.count returns undefined, because count isn't a property on the function. Typing count on its own throws a ReferenceError: count is not defined, because it isn't a global either. That error is the result you want. It means only counter can touch the value.

Finally, create a second counter and call it. It should return 1, not 3, which confirms that each closure has its own separate count.

  • Repeated calls return 1, then 2, then 3
  • counter.count returns undefined
  • count on its own throws a ReferenceError
  • A new counter starts again at 1

Fix the three most common closure mistakes

Your counter works, but closures in real code can surprise you. Almost every surprise comes down to one question: which binding did the function actually capture? The live link that makes your counter work is the same thing behind each of these bugs.

The first is var in loops, where every callback ends up seeing the final value. The second is a stale value, where a closure captured outdated state. The third is a leaked reference, where a closure keeps large objects alive longer than you need. When something behaves strangely, ask what the function is holding on to, and you'll usually find the cause quickly.

  • var in loops: declare the loop variable with let instead
  • Stale value: re-create the closure, or read the current state
  • Leaked reference: remove listeners and drop references you no longer need

Trace why var breaks loop callbacks

The var loop bug is the classic closure trap and a common interview question. Picture a loop written as for (var i = 0; i < 3; i++) that schedules a setTimeout on each pass, with each callback logging i.

Step through it. The loop runs with i at 0, 1 and 2, but var makes i a single function-scoped variable. Three setTimeout callbacks are queued, all capturing that same i. When the loop ends, the shared i equals 3. When the callbacks finally run, they log 3, 3, 3.

Switch the declaration to let and the result changes. Because let is block-scoped, each pass of the loop gets its own new binding, so each callback closes over its own i and you see 0, 1, 2. The lesson is to count bindings, not values: with var there's one binding shared by all three callbacks, and with let there are three.

  • With var, all callbacks share one i
  • With let, each iteration gets a fresh i
  • Closures capture variables, not snapshots of values

Key takeaways

  • The outer function declares count and keeps it out of reach.
  • The inner function reads and updates count through its enclosing scope.
  • Call createCounter once and store the function it returns.
  • The lexical environment stays alive while something can reach it, and that's the closure.
  • Use let in loops and release references you no longer need.
  • Functions remember where they were written, so you can use that for privacy and state.

Frequently asked questions

What is a closure in JavaScript?

A closure is a function together with the lexical environment it was written in. It lets the function keep using variables from that outer scope, even after the outer function has returned.

Why doesn't the variable disappear when the outer function returns?

The returned function keeps a reference to its lexical environment. The garbage collector only frees memory that nothing can reach, and because your stored function can still reach that environment, the variable stays alive.

Why use let instead of const for the counter variable?

The counter's value changes on every call, so the variable has to be reassigned. A const binding can't be reassigned, so incrementing it would throw a TypeError.

Do two counters made with createCounter share the same count?

No. Each call to createCounter creates a fresh count and a new inner function. A second counter starts at zero and returns 1 on its first call, however many times the first counter has been used.

Why does a var loop with setTimeout log the same number three times?

With var, the loop variable is a single function-scoped binding, so all the callbacks capture the same i. By the time they run, the loop has finished and i is 3. Declaring the loop variable with let gives each iteration its own binding, so the callbacks log 0, 1, 2.

Can closures cause memory problems?

They can if a closure keeps large objects reachable after you're done with them. The fix is to remove listeners and drop references you no longer need, so that memory can be freed.

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
Ad