A closure is a function together with the variables from its surrounding scope that it refers to. Even after the outer function has returned, the inner function still has access to those variables.
Why it matters
Closures let you create functions with private, persistent state, configure behavior in one place and use it in another, and write callbacks that remember context. They are central to JavaScript, Python, Ruby, Swift, Kotlin and most modern languages. They also have a cost: captured variables stay alive as long as the closure does, which can cause memory leaks or surprising behavior when the captured variable changes later.
Example
function counter() {
let n = 0;
return () => ++n;
}
const next = counter();
next(); // 1
next(); // 2
The returned function keeps its own n. A second call to counter() creates a separate closure with its own count.
Common mistakes
- Capturing a loop variable declared with
varin JavaScript, so every closure sees the final value. - Holding large objects in a closure longer than needed.
- Mistaking a closure for a copy of the variable; it keeps a live reference to the original.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
यह पेज सामान्य जानकारी है, जिसे हमारी संपादकीय टीम ने लिखा है और दस्तावेज़ीकरण बदलने पर अपडेट किया जाता है। सर्वर और प्रदाता अलग-अलग होते हैं, इसलिए बदलाव पहले सुरक्षित तरीके से जाँचें। देखें: संपादकीय नीति और अस्वीकरण.