100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogJavaScript Closures Explained With Examples
Programming

JavaScript Closures Explained With Examples

SV

SkillVeris Team

Engineering Team

Apr 26, 2026 11 min read
Share:
JavaScript Closures Explained With Examples
Key Takeaway

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.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Engineering Team

Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse