[{"data":1,"prerenderedAt":189},["ShallowReactive",2],{"qa-\u002Fjavascript\u002Ffunctions\u002Fclosures":3},{"page":4,"siblings":169,"blog":186},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":161,"seo":162,"seoDescription":163,"stem":164,"subtopic":6,"topic":165,"topicSlug":166,"updated":167,"__hash__":168},"qa\u002Fjavascript\u002Ffunctions\u002Fclosures.md","Closures",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","JavaScript","javascript",{},true,1,"\u002Fjavascript\u002Ffunctions\u002Fclosures",[23,27,31,36,40,44,48,53,57,61,65,69,73,77,81,85,89,93,97,101,105,109,113,117,121,125,129,133,137,141,145,149,153,157],{"id":24,"difficulty":14,"q":25,"a":26},"what-is-closure","What is a closure?","A closure is a function bundled together with a **reference to the lexical\nscope in which it was created**. Because of that bundle, the inner function\nkeeps access to its outer variables **even after the outer function has\nreturned** and that outer call's scope would otherwise be gone.\n\n```js\nfunction counter() {\n  let count = 0           \u002F\u002F lives in counter's scope\n  return () => ++count    \u002F\u002F this arrow closes over `count`\n}\n\nconst next = counter()    \u002F\u002F counter() has returned...\nnext() \u002F\u002F 1               \u002F\u002F ...yet `count` is still alive and remembered\nnext() \u002F\u002F 2\n```\n\nThe key insight interviewers want: the closure captures the **variable itself\n(the binding), not a copy of its value**. So `count` is genuinely shared and\nmutable across calls — each `next()` sees and updates the same `count`. Every\nfunction in JavaScript is technically a closure; it only *matters* when the\nfunction outlives the scope it captured.\n",{"id":28,"difficulty":14,"q":29,"a":30},"closure-use","What are practical uses of closures?","Closures are everywhere in real JavaScript, usually to **remember state\nbetween calls** without a global variable or a class:\n\n- **Data privacy \u002F encapsulation** — the module pattern, private counters,\n  anything you don't want callers to touch directly.\n- **Function factories & currying \u002F partial application** — pre-fill some\n  arguments and return a specialized function.\n- **Callbacks & event handlers** — a handler remembers the data it was set up\n  with.\n- **Memoization** — keep a private cache between invocations.\n\n```js\nfunction memoize(fn) {\n  const cache = new Map()        \u002F\u002F private, persists across calls\n  return arg => {\n    if (cache.has(arg)) return cache.get(arg)\n    const result = fn(arg)\n    cache.set(arg, result)\n    return result\n  }\n}\n```\n",{"id":32,"difficulty":33,"q":34,"a":35},"closure-memory","hard","Can closures cause memory leaks?","Yes. A closure keeps its captured scope alive for as long as the closure\nitself is reachable. If that closure outlives its usefulness while holding\nreferences to **large objects or detached DOM nodes**, the garbage collector\ncan't reclaim them — a leak.\n\n```js\nfunction attach() {\n  const huge = new Array(1_000_000).fill('🐘')\n  document.getElementById('btn').addEventListener('click', () => {\n    \u002F\u002F this handler closes over `huge`, pinning it in memory forever\n    console.log(huge.length)\n  })\n}\n```\n\nMitigations: remove event listeners when you're done\n(`removeEventListener`), null out references you no longer need, avoid\ncapturing more than necessary, and consider `WeakMap`\u002F`WeakRef` for caches so\nentries can be collected when nothing else references the key.\n",{"id":37,"difficulty":33,"q":38,"a":39},"closure-loop","How do closures explain the classic for-loop var bug?","With `var`, the loop variable is **function-scoped**, so there's a *single*\nbinding shared by every iteration. By the time the deferred callbacks run, the\nloop has finished and they all read that one binding's **final value**. `let`\nis **block-scoped** and creates a **fresh binding per iteration**, so each\ncallback closes over its own copy.\n\n```js\n\u002F\u002F all share one `i`, which is 3 when the timeouts fire\nfor (var i = 0; i \u003C 3; i++) setTimeout(() => console.log(i)) \u002F\u002F 3 3 3\n\n\u002F\u002F a new `i` per iteration\nfor (let i = 0; i \u003C 3; i++) setTimeout(() => console.log(i)) \u002F\u002F 0 1 2\n```\n\nBefore `let` existed, the fix was to create a new scope manually with an IIFE:\n`(j => setTimeout(() => console.log(j)))(i)`. This question is really testing\nwhether you understand *binding vs value* capture.\n",{"id":41,"difficulty":14,"q":42,"a":43},"private-vars","How do you create private variables with closures?","Declare variables in an enclosing function scope and return only the functions\nthat should be allowed to touch them. The variables are unreachable from\noutside — there's no reference to them except through the methods you exposed.\n\n```js\nfunction account() {\n  let balance = 0 \u002F\u002F truly private — no outside access\n  return {\n    deposit: n => (balance += n),\n    withdraw: n => (balance -= n),\n    get: () => balance,\n  }\n}\n\nconst a = account()\na.deposit(100)\na.get()       \u002F\u002F 100\na.balance     \u002F\u002F undefined — can't reach the closed-over variable\n```\n\nThis was the canonical way to get encapsulation before JavaScript added\n`#private` class fields, and it still underlies the module pattern.\n",{"id":45,"difficulty":14,"q":46,"a":47},"currying","What is currying and how do closures enable it?","Currying transforms a function that takes **many arguments** into a **chain of\nfunctions that each take one**. Closures make it work: each returned function\n*remembers* the arguments supplied to the earlier ones via its captured scope.\n\n```js\nconst add = a => b => c => a + b + c\nadd(1)(2)(3) \u002F\u002F 6\n\n\u002F\u002F practical: build specialized functions by partially applying\nconst multiply = a => b => a * b\nconst double = multiply(2) \u002F\u002F remembers a = 2\ndouble(10) \u002F\u002F 20\n```\n\nEach inner arrow closes over the parameters of the outer arrows, which is why\n`double` keeps `a = 2` ready for whenever you call it. Useful for\nconfiguration, reusable utilities, and point-free function composition.\n",{"id":49,"difficulty":50,"q":51,"a":52},"iife","easy","What is an IIFE and why was it used?","An **Immediately Invoked Function Expression** is a function that runs the\ninstant it's defined — you wrap it in parentheses to make it an *expression*\nand immediately call it with `()`.\n\n```js\n(function () {\n  const secret = 42 \u002F\u002F scoped to here, not global\n  console.log(secret)\n})()\n```\n\nBefore block scoping (`let`\u002F`const`) and ES modules, the IIFE was the main tool\nfor creating a **private scope**: it kept variables out of the global namespace\n(avoiding name collisions between scripts) and was the backbone of the module\npattern. Today `let`\u002F`const` blocks and real modules cover most of these cases,\nso you see IIFEs less often.\n",{"id":54,"difficulty":14,"q":55,"a":56},"closure-vs-scope","What is the difference between scope and a closure?","They're related but not the same thing:\n\n- **Scope** is a *static* concept: the set of variables accessible at a given\n  location in your code, determined by where things are written (lexical\n  scoping). It exists whether or not any function \"leaves.\"\n- A **closure** is what you get at *runtime* when a function **retains access to\n  its defining scope and carries it along** to be executed somewhere else —\n  after the outer function has returned.\n\n```js\nfunction outer() {\n  const x = 10        \u002F\u002F x is in outer's SCOPE\n  return () => x      \u002F\u002F the returned function + its hold on x = a CLOSURE\n}\nconst fn = outer()    \u002F\u002F outer's scope is gone, but the closure keeps x alive\nfn() \u002F\u002F 10\n```\n\nPut simply: scope defines *what a function can see*; a closure is the function\n*remembering and preserving* that view beyond its original lifetime.\n",{"id":58,"difficulty":14,"q":59,"a":60},"module-pattern","What is the module pattern?","The module pattern uses a closure (classically an IIFE) to create **private\nstate** and expose only a public API — the returned object's methods close over\nvariables that are otherwise inaccessible.\n\n```js\nconst counter = (function () {\n  let count = 0                  \u002F\u002F private\n  return {\n    increment() { count++ },\n    value() { return count },\n  }\n})()\ncounter.increment()\ncounter.value()  \u002F\u002F 1\ncounter.count    \u002F\u002F undefined — truly private\n```\n\nIt was the standard way to organize code and hide internals before ES modules.\nToday `import`\u002F`export` modules serve the same purpose at the file level, but the\npattern still appears for encapsulated singletons.\n",{"id":62,"difficulty":33,"q":63,"a":64},"debounce","How do you implement debounce with a closure?","Debounce delays running a function until input **stops** for a quiet period. A\nclosure holds the pending timer id across calls so each new call can cancel the\nprevious one.\n\n```js\nfunction debounce(fn, delay) {\n  let timer                      \u002F\u002F remembered between calls via closure\n  return function (...args) {\n    clearTimeout(timer)\n    timer = setTimeout(() => fn.apply(this, args), delay)\n  }\n}\nconst onSearch = debounce(query => fetchResults(query), 300)\n```\n\nEach keystroke resets the timer; `fn` runs only 300ms after the **last** call.\nThe private `timer` variable is exactly the kind of persistent state closures\nexist for.\n",{"id":66,"difficulty":33,"q":67,"a":68},"throttle","How does throttle differ from debounce, and how do you implement it?","**Throttle** runs the function **at most once per interval** (regular cadence),\nwhereas **debounce** waits until activity stops. A closure tracks the last run\ntime.\n\n```js\nfunction throttle(fn, limit) {\n  let last = 0\n  return function (...args) {\n    const now = Date.now()\n    if (now - last >= limit) {\n      last = now\n      fn.apply(this, args)\n    }\n  }\n}\nconst onScroll = throttle(() => updatePosition(), 100)\n```\n\nUse **throttle** for continuous events where you want steady updates (scroll,\nresize, mousemove); use **debounce** for \"act after they finish\" (search input,\nautosave).\n",{"id":70,"difficulty":14,"q":71,"a":72},"once","How do you write a once() function?","`once` wraps a function so it runs **only the first time** and returns the cached\nresult thereafter. A closure remembers whether it has been called and the result.\n\n```js\nfunction once(fn) {\n  let called = false, result\n  return function (...args) {\n    if (!called) {\n      called = true\n      result = fn.apply(this, args)\n    }\n    return result\n  }\n}\nconst init = once(() => console.log('init!'))\ninit() \u002F\u002F 'init!'\ninit() \u002F\u002F (nothing — cached)\n```\n\nUseful for one-time initialization, idempotent event handlers, and lazy\nsingletons.\n",{"id":74,"difficulty":33,"q":75,"a":76},"memoize","How do you implement memoization with a closure?","Memoization caches results of expensive pure functions by their arguments. A\nclosure holds a private cache that persists across calls.\n\n```js\nfunction memoize(fn) {\n  const cache = new Map()        \u002F\u002F private, lives between calls\n  return function (...args) {\n    const key = JSON.stringify(args)\n    if (cache.has(key)) return cache.get(key)\n    const result = fn.apply(this, args)\n    cache.set(key, result)\n    return result\n  }\n}\nconst slowSquare = memoize(n => n * n)\n```\n\nThe cache is invisible to callers — pure encapsulation. Only memoize **pure**\nfunctions, and mind cache growth (a `WeakMap` or LRU cap helps for large key\nspaces).\n",{"id":78,"difficulty":14,"q":79,"a":80},"partial-application","What is partial application and how do closures enable it?","Partial application **fixes some arguments** of a function now, returning a new\nfunction that takes the rest later. The returned function closes over the\npre-supplied arguments.\n\n```js\nfunction partial(fn, ...preset) {\n  return (...rest) => fn(...preset, ...rest) \u002F\u002F closes over `preset`\n}\nconst add = (a, b, c) => a + b + c\nconst add10 = partial(add, 10)\nadd10(20, 30) \u002F\u002F 60\n```\n\nIt differs from currying (which takes args one at a time); partial application\nfixes any number at once. Both rely on closures to remember the bound arguments.\n",{"id":82,"difficulty":14,"q":83,"a":84},"event-handler-state","How do closures help event handlers keep state?","An event handler defined inside a function closes over that function's variables,\nso each handler \"remembers\" the data it was created with — without needing global\nstate or data attributes.\n\n```js\nfunction setupButtons(labels) {\n  labels.forEach((label, i) => {\n    button[i].addEventListener('click', () => {\n      console.log(`clicked ${label} (#${i})`) \u002F\u002F closes over label and i\n    })\n  })\n}\n```\n\nEach handler captures its own `label`\u002F`i`. (Using `let`\u002F`forEach` gives a fresh\nbinding per iteration — the same reason the classic `var` loop bug doesn't\nappear here.)\n",{"id":86,"difficulty":33,"q":87,"a":88},"settimeout-puzzle","What does this setTimeout-in-a-loop snippet print and why?","```js\nfor (var i = 0; i \u003C 3; i++) {\n  setTimeout(() => console.log(i), 100)\n}\n\u002F\u002F 3 3 3\n```\n\nAll three arrow functions close over the **same** `var i` (function-scoped). By\nthe time the timers fire (after the loop completes), `i` is `3`. Fixes:\n\n```js\nfor (let i = 0; i \u003C 3; i++) setTimeout(() => console.log(i), 100) \u002F\u002F 0 1 2\n\u002F\u002F or capture per iteration with an IIFE:\nfor (var i = 0; i \u003C 3; i++) ((j) => setTimeout(() => console.log(j)))(i)\n```\n\nThe lesson: closures capture the **variable binding**, not a snapshot of its\nvalue.\n",{"id":90,"difficulty":33,"q":91,"a":92},"capture-reference","Do closures capture a variable's value or the variable itself?","Closures capture the **variable (binding), not a copy of its value**. So if the\nvariable changes after the closure is created, the closure sees the **new**\nvalue.\n\n```js\nlet x = 1\nconst read = () => x\nx = 99\nread() \u002F\u002F 99 — not 1\n```\n\nThis is why the `var` loop bug happens (all closures share one binding) and why\n`let` fixes it (a fresh binding each iteration). To capture a value snapshot,\ncopy it into a new scope (an IIFE parameter or a `let` in the loop body).\n",{"id":94,"difficulty":14,"q":95,"a":96},"lexical-scoping","What is lexical scoping and how does it relate to closures?","Lexical (static) scoping means a function's accessible variables are determined by\n**where it is written** in the source, not where it's called. Closures are the\nruntime consequence: a function carries its lexical environment with it.\n\n```js\nfunction outer() {\n  const secret = 42\n  function inner() { return secret } \u002F\u002F resolves `secret` by lexical position\n  return inner\n}\nouter()() \u002F\u002F 42 — inner remembers outer's scope wherever it runs\n```\n\nBecause scope is fixed at definition time, you can reason about what a closure can\naccess just by reading the nested structure of the code.\n",{"id":98,"difficulty":14,"q":99,"a":100},"each-call-new-closure","Does each function call create a new closure?","Yes. Every invocation of an outer function creates a **fresh scope**, so any inner\nfunctions returned capture **independent** copies of that scope. Two calls to a\nfactory produce two unrelated states.\n\n```js\nfunction counter() { let n = 0; return () => ++n }\nconst a = counter()\nconst b = counter()\na() \u002F\u002F 1\na() \u002F\u002F 2\nb() \u002F\u002F 1 — separate closure, separate `n`\n```\n\nThis independence is what makes closure-based factories useful: each produced\nobject has its own private state.\n",{"id":102,"difficulty":50,"q":103,"a":104},"function-factory","What is a function factory?","A function factory is a function that **returns customized functions**, each\nclosing over the arguments used to create it. It's a clean way to generate\nspecialized variants.\n\n```js\nfunction makeMultiplier(factor) {\n  return n => n * factor   \u002F\u002F closes over `factor`\n}\nconst double = makeMultiplier(2)\nconst triple = makeMultiplier(3)\ndouble(5) \u002F\u002F 10\ntriple(5) \u002F\u002F 15\n```\n\nEach returned function remembers its own `factor`. Factories built on closures\npower currying, partial application, and configurable utilities.\n",{"id":106,"difficulty":33,"q":107,"a":108},"closures-and-this","Do closures capture this?","No — a closure captures **variables** from its lexical scope, but `this` is **not**\na normal variable for regular functions; it's set by how the function is called.\n**Arrow functions**, however, capture `this` lexically (like a closed-over\nvariable).\n\n```js\nconst obj = {\n  name: 'Ada',\n  regular() { return function () { return this.name } }, \u002F\u002F `this` lost\n  arrow()   { return () => this.name },                  \u002F\u002F `this` captured\n}\nobj.regular()() \u002F\u002F undefined (this is not obj)\nobj.arrow()()   \u002F\u002F 'Ada'  (arrow closes over obj's this)\n```\n\nA common pre-arrow workaround was `const self = this`, which *does* capture `this`\nas an ordinary closed-over variable.\n",{"id":110,"difficulty":14,"q":111,"a":112},"closure-vs-class","How do closures compare to classes for encapsulation?","Both can hide state. **Closures** give true privacy via captured variables, with\na functional feel and no `this`. **Classes** are more familiar, support\ninheritance and (now) `#private` fields, and are more memory-efficient when you\ncreate many instances (methods live once on the prototype).\n\n```js\n\u002F\u002F closure\nconst make = () => { let n = 0; return { inc: () => ++n } }\n\u002F\u002F class\nclass C { #n = 0; inc() { return ++this.#n } }\n```\n\nClosures excel for small factories and one-offs; classes scale better for many\ninstances and rich hierarchies. With `#private` fields, classes now match\nclosures on genuine privacy.\n",{"id":114,"difficulty":14,"q":115,"a":116},"revealing-module","What is the revealing module pattern?","A variation of the module pattern where you define all functions\u002Fvariables\nprivately and **return an object that maps public names to those private\nmembers** — making the public API explicit at the bottom.\n\n```js\nconst calc = (function () {\n  let total = 0\n  function add(n) { total += n }\n  function get() { return total }\n  return { add, get }   \u002F\u002F \"reveal\" only these\n})()\n```\n\nIt improves readability (the exposed surface is listed in one place) and lets you\nrename the public API independently of the private implementation.\n",{"id":118,"difficulty":33,"q":119,"a":120},"generator-vs-closure","How do generators compare to closures for maintaining state?","Both keep state between calls. A **closure** holds state in captured variables a\nreturned function reads\u002Fwrites. A **generator** pauses at `yield` and resumes,\npreserving its entire execution state — better for **sequences** and lazy\niteration.\n\n```js\n\u002F\u002F closure counter\nconst counter = (() => { let n = 0; return () => ++n })()\n\u002F\u002F generator counter\nfunction* gen() { let n = 0; while (true) yield ++n }\nconst g = gen()\ng.next().value \u002F\u002F 1\n```\n\nUse a closure for simple persistent state; a generator when you need to produce a\nstream of values or model a resumable process.\n",{"id":122,"difficulty":33,"q":123,"a":124},"closure-react-stale","How do closures cause stale values in callbacks (e.g. React)?","A callback closes over the variables from the moment it was **created**. If those\nvalues change later but the callback isn't recreated, it keeps using the old\n(\"stale\") snapshot.\n\n```js\nlet count = 0\nconst timer = setInterval(() => console.log(count), 1000) \u002F\u002F always logs 0\ncount = 5 \u002F\u002F the closure captured the binding, but in React each render has its own\n```\n\nIn React, each render creates new closures over that render's props\u002Fstate, so an\neffect or event handler with stale deps logs old values. Fixes: include the value\nin dependencies, use a functional updater, or read the latest from a `ref`.\n",{"id":126,"difficulty":33,"q":127,"a":128},"closure-gc","When is a closure's captured scope garbage collected?","A closure keeps its captured variables alive **as long as the closure itself is\nreachable**. Once nothing references the closure, the captured scope becomes\neligible for garbage collection.\n\n```js\nfunction make() {\n  const big = new Array(1e6)\n  return () => big.length\n}\nlet fn = make()  \u002F\u002F `big` is retained because fn closes over it\nfn = null        \u002F\u002F now `big` can be collected\n```\n\nEngines optimize by capturing only the variables actually used, but holding onto\nclosures (e.g. in a long-lived array or an un-removed event listener)\nindefinitely retains their scope — a common leak source.\n",{"id":130,"difficulty":14,"q":131,"a":132},"nested-closures","How do nested closures work?","An inner function can close over variables from **multiple enclosing scopes** at\nonce, walking up the scope chain. Each level's variables remain accessible.\n\n```js\nfunction a(x) {\n  return function b(y) {\n    return function c(z) {\n      return x + y + z   \u002F\u002F closes over x (from a) AND y (from b)\n    }\n  }\n}\na(1)(2)(3) \u002F\u002F 6\n```\n\nThis layered capture is exactly how currying works. The innermost function holds\nreferences to every outer scope it uses, keeping them all alive.\n",{"id":134,"difficulty":50,"q":135,"a":136},"closure-array-methods","How do closures appear in array method callbacks?","Callbacks passed to `map`\u002F`filter`\u002F`reduce` close over variables in their\nsurrounding scope, letting them reference outside data without extra parameters.\n\n```js\nfunction aboveThreshold(numbers, threshold) {\n  return numbers.filter(n => n > threshold) \u002F\u002F closes over `threshold`\n}\naboveThreshold([1, 5, 10], 4) \u002F\u002F [5, 10]\n```\n\nThe arrow remembers `threshold` from the enclosing function. This is closures at\nwork in everyday code, usually without anyone calling it \"a closure.\"\n",{"id":138,"difficulty":33,"q":139,"a":140},"shared-state-bug","What bug arises when closures unexpectedly share state?","If multiple closures capture the **same** variable (instead of separate\nbindings), they all see and mutate one shared value — leading to surprising\ncoupling, like the `var` loop bug.\n\n```js\n\u002F\u002F all handlers share one `config` object\nconst config = {}\nconst handlers = sources.map(() => () => use(config)) \u002F\u002F same config\n```\n\nTo give each closure its own state, create a fresh scope per closure (a factory\ncall, an IIFE, or a block-scoped `let`). Recognizing shared vs independent capture\nis key to debugging closure issues.\n",{"id":142,"difficulty":14,"q":143,"a":144},"closure-async-await","How do closures behave across async boundaries?","Variables captured by a closure remain valid **after** awaits and across async\ngaps — the closure keeps the scope alive. But beware capturing a value that\n**changes** during the wait.\n\n```js\nasync function process(items) {\n  for (const item of items) {\n    await save(item)\n    \u002F\u002F `item` is correctly captured per iteration (let\u002Fconst)\n  }\n}\n```\n\n`let`\u002F`const` loop variables give each iteration a fresh binding, so async\ncallbacks see the right value. With `var`, the shared binding would be stale by\nthe time the awaited work resumes.\n",{"id":146,"difficulty":50,"q":147,"a":148},"counter-with-operations","How do you build an encapsulated counter with multiple operations?","Return an object whose methods all close over the same private variable, so they\nshare controlled access to it while the outside world can't touch it directly.\n\n```js\nfunction createCounter(start = 0) {\n  let count = start\n  return {\n    increment: () => ++count,\n    decrement: () => --count,\n    reset: () => (count = start),\n    value: () => count,\n  }\n}\nconst c = createCounter(10)\nc.increment(); c.value() \u002F\u002F 11\n```\n\nAll four methods operate on one private `count`. This is the closure-based\nalternative to a class with a private field.\n",{"id":150,"difficulty":14,"q":151,"a":152},"closure-loop-fix-iife","How does an IIFE fix the var loop closure problem?","An IIFE creates a **new scope per iteration**, capturing the current value as a\nparameter so each callback closes over its own copy.\n\n```js\nfor (var i = 0; i \u003C 3; i++) {\n  (function (j) {\n    setTimeout(() => console.log(j), 100) \u002F\u002F j is this iteration's copy\n  })(i)\n}\n\u002F\u002F 0 1 2\n```\n\nThe IIFE is immediately invoked with `i`, binding it to the local `j`. This was\nthe standard pre-ES6 fix; today simply using `let` (which block-scopes per\niteration) is cleaner.\n",{"id":154,"difficulty":14,"q":155,"a":156},"closure-overhead","Do closures have a performance or memory cost?","Each closure retains its captured variables in memory for as long as it lives, so\ncreating **many** closures (e.g. a new function per array element in a hot loop)\nuses more memory than sharing one function. Modern engines optimize aggressively,\ncapturing only used variables.\n\n```js\n\u002F\u002F creates N closures, each retaining scope\nitems.map(item => () => process(item))\n```\n\nIn practice closures are cheap and the readability\u002Fencapsulation wins outweigh the\ncost — but in performance-critical code with huge numbers of closures, reusing\nfunctions or avoiding unnecessary capture can matter.\n",{"id":158,"difficulty":14,"q":159,"a":160},"closure-singleton","How do you implement a singleton with a closure?","An IIFE runs once and returns a single shared instance; the closure caches it so\nevery access returns the same object.\n\n```js\nconst config = (function () {\n  let instance\n  function create() { return { loadedAt: Date.now() } }\n  return {\n    get() {\n      if (!instance) instance = create() \u002F\u002F created once\n      return instance\n    },\n  }\n})()\nconfig.get() === config.get() \u002F\u002F true — same instance\n```\n\nThe private `instance` variable, hidden in the closure, guarantees a single\nshared object — the closure-based singleton pattern.\n",null,{"description":11},"JavaScript closure interview questions and answers — what closures are, how they capture variables, practical uses and common pitfalls.","javascript\u002Ffunctions\u002Fclosures","Functions","functions","2026-06-17","fIkqXiaH8g__RSSbGGQQ3i6Y8gV63cRtxHtJRDtN9gg",[170,171,174,178,182],{"subtopic":6,"path":21,"order":20},{"subtopic":172,"path":173,"order":12},"The this Keyword","\u002Fjavascript\u002Ffunctions\u002Fthis-keyword",{"subtopic":175,"path":176,"order":177},"Higher-Order Functions","\u002Fjavascript\u002Ffunctions\u002Fhigher-order-functions",3,{"subtopic":179,"path":180,"order":181},"Function Types & Parameters","\u002Fjavascript\u002Ffunctions\u002Ffunction-types-parameters",4,{"subtopic":183,"path":184,"order":185},"Generators & Iterators","\u002Fjavascript\u002Ffunctions\u002Fgenerators-iterators",5,{"path":187,"title":188},"\u002Fblog\u002Fjavascript-closures-explained-patterns","JavaScript Closures Explained — From Basics to Advanced Patterns",1781808675977]