Glossary · Programming

Closure

A closure is a function bundled with the variables from the scope where it was created, so it can keep using them after that scope has finished.

Updated October 6, 2026

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 var in 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.

Get notified when this term updates

Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.

This page is general information written by our editorial team and updated when documentation changes. Servers and providers differ, so test changes safely first. See our editorial policy and disclaimer.