{"post":{"slug":"what-is-a-closure-in-javascript-2026","title":"What is a closure in JavaScript in 2026? Plain-English guide","excerpt":"A closure is a function that remembers the variables from where it was created, even after that outer code has finished running. Here is what that enables.","category":"code","date":"July 17, 2026","author":"ByteLedger Team","content":"<span class=\"dropcap\">A</span> closure is a function that remembers the variables from the place it was created, even after that outer code has already finished running. Every function you write in JavaScript is technically a closure over its surrounding scope; most just do not happen to reference anything outside themselves, so the behavior stays invisible. Once a function does reach outside itself, and gets returned or passed somewhere else, that memory is what makes private variables, function factories, and a lot of everyday patterns possible.\n\n## What changed in 2026\n\n- **Framework docs now teach closures before hooks.** React's official material and most 2026 bootcamps introduce closures explicitly before `useState` and `useEffect`, because those hooks are close to impossible to reason about without understanding what a function remembers.\n- **AI assistants explain closures well but still generate closure bugs.** Paste a specific closure problem into an assistant and the explanation is usually solid, but the same assistant will still generate a `setTimeout` or event-handler callback that captures a stale value. Read anything generated that reaches outside its own scope.\n- **Modern bundlers optimize closures aggressively.** Tools like esbuild and swc make the old advice to avoid closures in hot paths for performance reasons matter far less in 2026 than it did a decade ago.\n\n## The basic idea\n\n```js\nfunction makeGreeter(name) {\n  const greeting = \"Hello, \" + name;\n  return function () {\n    console.log(greeting); // remembers `greeting`\n  };\n}\n\nconst greetSam = makeGreeter(\"Sam\");\ngreetSam(); // \"Hello, Sam\" — runs long after makeGreeter finished\n```\n\n`greetSam` still has access to `greeting`, even though `makeGreeter` already returned. The inner function carries its surrounding scope along with it, like a backpack it never puts down.\n\n## Using closures for private data\n\n```js\nfunction createAccount(startingBalance) {\n  let balance = startingBalance; // not reachable from outside directly\n\n  return {\n    deposit(amount) { balance += amount; return balance; },\n    withdraw(amount) { balance -= amount; return balance; },\n    getBalance() { return balance; },\n  };\n}\n\nconst account = createAccount(100);\naccount.deposit(50);\nconsole.log(account.getBalance()); // 150\n```\n\n`balance` only exists inside the closure. Nothing outside `createAccount` can touch it directly, which is close to a private field, without using the newer `#private` class syntax.\n\n## Function factories\n\n```js\nfunction makeMultiplier(factor) {\n  return (n) => n * factor;\n}\n\nconst double = makeMultiplier(2);\nconst triple = makeMultiplier(3);\ndouble(5); // 10\ntriple(5); // 15\n```\n\nEach call to `makeMultiplier` creates a fresh, independent `factor`. `double` and `triple` do not interfere with each other, because each closure has its own copy of the surrounding scope.\n\n## Where closures show up without you naming them\n\n| Everyday pattern | Where the closure is |\n| --- | --- |\n| An event listener set up with a config value | The handler closes over the config passed to the setup function |\n| `useState` in React | The setter and the current value are tied together by a closure |\n| A `setTimeout` callback using an outer variable | The callback closes over whatever it references from the surrounding scope |\n| A module that exposes only a few functions | The private internals are closed over by the exposed functions |\n\n## Common mistakes\n\nA closure does not copy a variable's value at creation time; it keeps a live reference, so if the outer variable changes later, the closure sees the new value. Capturing more than needed, such as holding onto a large object through a closure, keeps that object in memory as long as the closure exists, even if only one small piece of it was actually needed. A `var` declared inside a loop behaves surprisingly inside a closure for a related reason: `var` is hoisted to function scope rather than block scope, so every closure created in the loop shares the same variable. See [what hoisting is in JavaScript](/blog/what-is-hoisting-in-javascript-2026) for why `var` behaves this way; switching to `let` is usually the fix.\n\n## FAQ\n\n**Do I have to nest functions to get a closure?**\nAn inner function needs to reference a variable from an enclosing scope, which in practice almost always means some form of nesting, whether a named function, an arrow function, or a callback.\n\n**Are closures unique to JavaScript?**\nNo. Python, Rust, Swift, and many other languages have closures. The core idea, a function that remembers its defining scope, is the same everywhere, though syntax and rules differ.\n\n**Do closures cause memory leaks?**\nThey can keep variables alive longer than expected if the closure itself is kept alive, such as an event listener that is never removed. It is a real consideration, though rarely a practical problem for typical application code.\n\n**Is an arrow function a closure?**\nAn arrow function is a closure whenever it references a variable from its surrounding scope, exactly like a regular function. The arrow syntax changes how `this` is handled, not the closure behavior itself.\n\n## Where to go next\n\n- [What is hoisting in JavaScript in 2026](/blog/what-is-hoisting-in-javascript-2026)\n- [What is the event loop in 2026](/blog/what-is-the-event-loop-2026)\n- [Callbacks vs promises vs async await in 2026](/blog/callbacks-vs-promises-vs-async-await-2026)","hue":240,"metaTitle":"What Is a Closure in JavaScript 2026? Guide","metaDescription":"What is a closure in JavaScript in 2026? A plain-English guide to how closures remember variables, with private counter and factory examples.","keywords":["closure in javascript 2026","what is a closure","javascript closure example","closure private variables","closure for beginners","function factory javascript","javascript scope chain","closure counter example","closures explained simply","javascript closure use cases"],"tldr":["**A closure is a function that keeps access to variables from where it was defined** — even after the outer function has already returned.","**Every function in JavaScript is a closure over its surrounding scope** — most just do not happen to use anything from outside themselves.","**Closures are how you fake private variables in JavaScript** — a variable only reachable through the functions you deliberately expose.","**Function factories return specialized functions using a closure** — one outer function, many independently configured inner functions.","**Skip:** wrapping simple values in a closure just to feel clever; if a variable does not need to be private or remembered across calls, a plain variable is clearer."],"readTime":"4 min read","wordCount":839},"related":[{"slug":"what-is-a-database-transaction-2026","title":"What is a database transaction? The 2026 plain-English guide","excerpt":"A transaction groups several database operations into one unit that either all happen or none do. Here is the lifecycle, not the isolation-level deep dive.","category":"code","date":"July 17, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":290},{"slug":"what-is-an-argument-2026","title":"What Is an Argument in 2026? Plain Programming Guide","excerpt":"A clear explanation of what an argument is in programming in 2026, how it passes data into a function, and how it differs from a parameter.","category":"code","date":"May 13, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":212},{"slug":"what-is-hoisting-in-javascript-2026","title":"What is hoisting in JavaScript in 2026? var, let, and const","excerpt":"Hoisting moves variable and function declarations to the top of their scope before code runs. Here is how var, let, const, and functions actually behave.","category":"code","date":"July 23, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":260}],"sameCategory":[{"slug":"bazel-build-explained-2026","title":"Bazel Explained: What Hermetic Builds Actually Cost","excerpt":"Bazel delivers reproducible, precisely cached builds and demands that you describe everything. Here is what you get, what it costs, and who should say no.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":145},{"slug":"graphql-federation-2026","title":"GraphQL Federation: One Graph, Many Teams","excerpt":"Federation composes independently-owned subgraphs into a single API. Here is what it solves, the operational cost it adds, and when a simpler gateway is enough.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":300},{"slug":"hermetic-builds-explained-2026","title":"Hermetic Builds Explained: Same Inputs, Same Output","excerpt":"A hermetic build depends only on declared inputs. Here is what that property gives you, the common leaks that break it, and how to move toward it incrementally.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":130},{"slug":"monorepo-tooling-compared-2026","title":"Monorepo Tooling Compared: What You Actually Need","excerpt":"Monorepo tools solve task orchestration and caching, not repository layout. Here is what each tier provides and how to tell when you have outgrown the simple option.","category":"code","date":"August 19, 2026","author":"ByteLedger Team","readTime":"3 min read","hue":150}],"newer":{"slug":"what-is-a-charitable-remainder-trust-2026","title":"Charitable remainder trusts in 2026, explained plainly","excerpt":"A charitable remainder trust pays you income for years and gives what is left to charity. Here is how it works, who it fits, and where it differs from simpler giving vehicles in 2026.","category":"finance","date":"July 17, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":200},"older":{"slug":"what-is-a-cold-backup-vs-hot-backup-2026","title":"Cold Backup vs Hot Backup in 2026: Key Differences","excerpt":"Cold backups are cheaper and slower to restore; hot backups cost more but come back online almost instantly. Here is how to tell which kind you actually need in 2026.","category":"tech","date":"July 17, 2026","author":"ByteLedger Team","readTime":"4 min read","hue":45}}