{
  "id": 2146707,
  "title": "A Beginners Guide To Closures",
  "url": "https://urgent.news/2026/08/20/a-beginners-guide-to-closures",
  "topic": "tech",
  "section": "Tech",
  "published": "2026-08-20T13:46:01.000Z",
  "source": {
    "name": "Dev.to",
    "slug": "dev-to",
    "url": "https://dev.to/kansoldev/a-beginners-guide-to-closuresu-1i1m"
  },
  "original_language": "en",
  "account": "Closures are a fundamental concept in JavaScript that allow a function to remember and access variables from the scope in which it was created, even after that outer scope has finished executing. This article explains what closures are, why they are useful, and provides a practical example to illustrate their behavior.\n\nA closure is formed when a function retains a reference to its lexical scope, which includes variables from the place it was created. In essence, closures enable functions to keep access to variables from their parent function, even after the parent function has returned. This is made possible because JavaScript functions maintain a reference to the environment they were born in, known as lexical scope.\n\nConsider the following simple example:\n```javascript\nfunction makeCounter() {\nlet x = 0;\nreturn function() {\nx++;\nconsole.log(x);\n};\n}\nconst increment = makeCounter();\nincrement(); // 1\nincrement(); // 2\n```\nIn this code, we immediately invoke `makeCounter()` and assign the returned inner function to the `increment` variable. Normally, one might expect the variable `x` to disappear once `makeCounter()` finishes execution. However, because the returned function references `x`, JavaScript keeps `x` alive in memory. Consequently, each call to `increment()` works with the same `x` value, not a fresh one. This behavior demonstrates how closures can maintain state across multiple function calls.\n\nClosures are particularly useful for solving problems related to variable persistence and scope management. Before closures were introduced, variables did not survive a function call in JavaScript. Each time a function was invoked, a new execution context was created, and any variables declared within that function were recreated. This meant that state could not persist between function calls without explicit workarounds, such as using global variables (which have drawbacks like being accessible and mutable from anywhere) or closures (whereby variables exist within the scope of the function).\n\nTo leverage closures effectively, it's crucial to understand the two key components: the outer function and the inner function. By creating an outer function that declares a variable in its local scope and then returning an inner function, you can establish a closure. The inner function can then access and manipulate the variable from the outer function's scope, even after the outer function has completed execution. This pattern is commonly used in various JavaScript scenarios, such as counters, caches, memoized functions, event handlers with private state, and the module pattern.\n\nHowever, it's essential to note that creating a closure and using it are two distinct actions. A common mistake occurs when one fails to invoke the outer function, resulting in the returned inner function being discarded without being utilized. In the following example, this mistake leads to the closure never being triggered:\n```javascript\ndocument.querySelector('#btn').addEventListener('click', getScore);\nfunction getScore() {\nlet score = 0;\nreturn function() {\nscore++;\nconsole.log(score);\n};\n}\n```\nIn this case, `getScore()` is registered as the click handler for the button with ID `#btn`. However, since `getScore()` itself is passed to `addEventListener()`, not the returned inner function, the closure is never executed. Each click creates a new `score` variable, increments it, and discards the inner function, leading to the counter never increasing.\n\nTo resolve this issue, the outer function must be called immediately so that its returned inner function becomes the event handler. Here's the corrected version:\n```javascript\ndocument.querySelector('#btn').addEventListener('click', getScore());\nfunction getScore() {\nlet score = 0;\nreturn function() {\nscore++;\nconsole.log(score);\n};\n}\n```\nBy invoking `getScore()` immediately, the returned inner function is assigned as the click event handler. Now, the closure persists across multiple clicks, incrementing `score` correctly each time.",
  "summary": "Introduction If you've been writing JavaScript for some time now, you've probably used a closure without realizing it, maybe in a setTimeout, an event listener, or a function that returns another function. Closures are one of those concepts that feel abstract in theory but are everywhere in practice once you know what to look for. They also have a reputation for being confusing, mostly because…",
  "key_points": [],
  "editors_take": null,
  "illustration": null,
  "coverage": {
    "outlets": 1,
    "also_reported_by": []
  },
  "ai_generated": true,
  "disclaimer": "Summaries, key points and the editor’s take are written by software from other outlets’ reporting and may contain errors — always check the linked original."
}