JavaScript Closures Explained With Examples
SkillVeris Team
Engineering Team

A closure is a function that remembers and can access variables from the scope where it was created, even after that outer function has finished running.
In this guide, you'll learn:
- Closures power essential JavaScript patterns including private data, function factories, memoization, and the callbacks used throughout event handling and asynchronous code.
- Every function in JavaScript forms a closure over its surrounding scope, so understanding them is fundamental to writing and debugging real-world code.
- The classic loop-variable bug is caused by var sharing one binding across iterations, and it is fixed cleanly by using let, which creates a fresh binding each time.
1What a Closure Actually Is
A closure is a function bundled together with the variables from the scope in which it was created, so it can keep using those variables even after the outer function has returned. In plain terms, a function remembers the environment it was born in. That memory is the entire idea, and everything else is a consequence of it.
This matters because functions in JavaScript are first-class values you can return from other functions and pass around. When an inner function references a variable from its enclosing function and then outlives that function, the variable does not disappear. The inner function holds onto it, keeping it alive for as long as the closure exists.
Closures are not an exotic feature you occasionally opt into; they are automatic and everywhere. Every time you define a function inside another scope and use a variable from outside it, you have created a closure. Understanding this quietly explains a huge amount of JavaScript behavior that otherwise seems mysterious.
2A Quick Refresher on Scope
To understand closures you first need scope, which is the set of variables accessible at a given point in your code. JavaScript has global scope, function scope, and block scope. A variable declared inside a function is normally invisible outside it, which is what keeps programs from turning into a tangle of name collisions.
Crucially, inner functions can see the variables of the functions that contain them, forming a chain. If a function is nested three levels deep, it can reach variables from all the enclosing levels up to the global scope. This nested visibility is called the scope chain, and it is the mechanism closures build upon.
The keywords let and const create block-scoped variables, meaning they live only within the nearest pair of curly braces, while the older var is function-scoped and ignores block boundaries. This difference is not academic; it is the root cause of one of the most famous closure bugs, which we will examine later.
3How a Closure Forms Step by Step
Imagine an outer function makeGreeter that takes a name and returns an inner function. The inner function uses the name variable to build a greeting when it is eventually called. When makeGreeter runs, it creates the name variable, defines the inner function, and returns it. Normally you would expect name to vanish once makeGreeter finishes.
But it does not vanish, because the returned inner function still references name. JavaScript keeps that variable alive as part of the closure, so calling the returned function later still produces the correct greeting. The outer function has long since returned, yet its variable persists inside the closure.
This is the whole mechanism in miniature. A function is created inside a scope, it captures a variable from that scope, and it is carried elsewhere still holding that variable. The captured variable is not a copy frozen in time; it is a live reference, which becomes important when we look at counters and the loop bug.
4Example: A Private Counter
The counter is the classic demonstration of closures. Picture a function makeCounter that declares a variable count set to zero and returns an inner function. Each time you call that inner function it increments count and returns the new value. The count variable lives inside the closure, invisible to the outside world.
When you call makeCounter, you get back a function. Calling it repeatedly yields one, then two, then three, because the same count variable persists between calls, held alive by the closure. Nothing outside can read or reset count directly; the only way to change it is through the function you were given.
This example reveals two powerful properties at once. The counter has state that survives between calls, and that state is genuinely private. If you create two separate counters, each has its own independent count, because each call to makeCounter creates a fresh scope and therefore a fresh closure. This independence is what makes closures so useful for building self-contained pieces of behavior.
5Closures for Data Privacy
JavaScript historically had no built-in notion of private fields, and closures filled that gap elegantly. By declaring variables inside a function and exposing only specific inner functions, you create data that outside code cannot touch except through the interface you allow. This is the foundation of the module pattern.
Imagine a function that creates a bank account object. Inside it you declare a balance variable, and you return an object with deposit and withdraw methods that adjust balance. Because balance lives in the closure and is never returned directly, no external code can set it to a nonsense value; it can only change through your controlled methods.
This pattern enforces invariants and hides implementation details, which is exactly what encapsulation is about. Even though modern JavaScript now offers class fields marked private with a hash symbol, closure-based privacy remains widespread, especially in libraries, and understanding it explains a great deal of the code you will read.
6Function Factories
A function factory is a function that builds and returns customized functions, and closures are what make it possible. Consider a function makeMultiplier that takes a factor and returns a new function which multiplies its argument by that factor. Calling makeMultiplier with three gives you a tripler; calling it with ten gives you a function that multiplies by ten.
Each returned function carries its own captured factor inside its closure, so they operate independently. This lets you generate a whole family of specialized functions from one general recipe, which keeps code concise and expressive. You configure behavior once and reuse the result many times.
Function factories appear constantly in real codebases, from building tailored event handlers to creating configured utility functions. Recognizing the pattern helps you both read library code and write flexible tools of your own, and it all rests on the simple fact that the returned function remembers the argument it was built with.
7Closures in Callbacks and Async Code
Closures are everywhere in asynchronous JavaScript, even when you do not name them. When you pass a callback to setTimeout, to an event listener, or to a promise, that callback often references variables from the surrounding function. It runs later, possibly long after the surrounding function returned, yet it still sees those variables thanks to the closure.
For example, attaching a click handler that logs a message stored in a nearby variable works because the handler closes over that variable. The browser fires the handler at some unpredictable future moment, and the message is still there, preserved by the closure exactly as it was when the handler was defined.
This is why closures are not an optional advanced topic but a daily reality. Nearly every event handler, timer, and asynchronous callback you write relies on closures to remember context. Once you see this, a lot of async behavior that felt like magic becomes predictable and explainable.
8The Classic Loop Variable Bug
The most infamous closure pitfall involves creating functions inside a loop. Suppose you loop with var i from zero to two and, on each iteration, schedule a setTimeout that logs i. Beginners expect to see zero, one, two, but with var they see three printed three times. The closures all captured the same shared i.
The reason is that var is function-scoped, so there is only one i variable shared across every iteration. By the time the delayed callbacks actually run, the loop has finished and i holds its final value. Each closure references that one variable, so they all report the same ending number rather than the value at their moment of creation.
The clean fix is to use let instead of var. Because let is block-scoped, each iteration of the loop gets its own fresh i binding, and each closure captures a distinct variable holding the value from that iteration. Switching one keyword turns the buggy output into the expected zero, one, two, which is a vivid lesson in why block scope matters.
9Closures for Memoization
Memoization is a technique that caches the results of expensive function calls so repeated calls with the same input return instantly, and closures provide a natural home for the cache. You wrap a function so that it keeps a private object mapping inputs to previously computed results, hidden inside the closure.
When the wrapped function is called, it first checks whether the input already exists in its cache. If so, it returns the stored answer without recomputing; if not, it computes the result, stores it, and returns it. The cache persists between calls precisely because it lives in the closure, surviving as long as the wrapped function does.
This pattern demonstrates how closures combine state and privacy for real performance benefits. The cache is invisible to callers, cannot be corrupted from outside, and grows organically as the function is used. Memoization built this way is a common tool for speeding up recursive or repeated computations.
10Common Mistakes and Misconceptions
A frequent misconception is that a closure captures the value of a variable at the moment it is created. In fact it captures the variable itself, a live reference, so if that variable changes later, the closure sees the new value. The loop bug is a direct consequence of misunderstanding this point.
Another mistake is creating closures unnecessarily inside hot loops or frequently called code, which can add memory overhead because each closure keeps its captured variables alive. Closures are cheap and idiomatic, but holding references to large objects longer than needed can prevent them from being garbage collected, a subtle source of memory leaks.
Finally, beginners sometimes overuse closures where a simpler structure would read better, wrapping everything in factory functions when a plain object or class would be clearer. Closures are a tool, not a goal. Reach for them when you genuinely want persistent private state, and prefer the simplest approach that expresses your intent.
11Why Interviewers Love Closures
Closures are a staple of JavaScript interviews because they test whether you truly understand scope, functions as values, and how variables live and die. A candidate who can explain the counter example, the module pattern, and the loop bug demonstrates a solid mental model rather than surface familiarity.
A very common interview task is to predict the output of a loop that creates functions with var, then explain why it misbehaves and how to fix it. Being able to walk through the shared-binding problem and offer both the let fix and the older approach of wrapping each iteration in its own function scope shows real depth.
Interviewers may also ask you to implement a private counter, a memoizer, or a function that can only be called once, all of which lean on closures. Practicing these small patterns until you can build them from memory is one of the highest-return preparations for a front-end or full-stack interview.
12How to Practice Closures on SkillVeris
Closures become second nature only through hands-on repetition, and SkillVeris is built for exactly that kind of learning. Its JavaScript and programming courses explain closures through a hobby you already enjoy, so the abstract idea of a function remembering its environment is anchored to something concrete and memorable rather than left floating in theory.
The most effective way to learn is to build the canonical examples yourself: a private counter, a function factory, a memoizer, and the loop bug together with its fix. Type each one, run it, change it, and predict the output before you check. That active loop of experimenting turns recognition into genuine understanding you can reproduce under pressure.
Pair the JavaScript material with the interview-preparation resources to rehearse explaining closures out loud, and with the broader data structures and algorithms track to round out your problem-solving. Because SkillVeris is free and personalized, you can drill closures alongside the rest of the fundamentals until they feel obvious, which is exactly the confidence a strong developer brings to real code.
Related Reading
Get The Print Version
Download a PDF of this article for offline reading.
About the Publisher
SkillVeris Team
Engineering Team
Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.
View all postsRelated Posts
Never miss an update
Get the latest tutorials and guides delivered to your inbox.
No spam. Unsubscribe anytime.