Skip to main content
AllDevToolsHub
Back to Glossary

Closure

A feature in JavaScript where an inner function has access to the outer function's variables even after the outer function has finished executing.

Detailed Explanation

Closures are created every time a function is defined inside another function. They allow for powerful patterns like data privacy (emulating private variables) and factory functions. A closure 'remembers' the environment in which it was created, which is essential for many functional programming techniques and state management patterns in modern JavaScript.

Quick Summary

A closure is a function bundled together with the variables from the scope in which it was defined. Even after the outer function returns, the inner function can still read and update those captured variables.

Key Takeaways

Key Takeaways

  • Every function in JavaScript is technically a closure, it captures the lexical scope around it.
  • Closures enable private state: variables visible only to functions returned from a factory.
  • They are how event handlers, setTimeout callbacks, and React hooks remember values from when they were created.
  • Captured variables are live references, not snapshots, mutations from outside are visible inside the closure.
  • Holding closures over large objects is a common cause of memory leaks because the GC cannot collect them.
Use Cases

When to use it

  • Implementing modules and private state before ES modules existed.
  • Currying and partial application in functional JavaScript.
  • Memoization helpers that store cached results in a closed-over Map.
  • React hooks like useState and useEffect rely on closures to retain values across renders.
Watch out

Common Mistakes

  • Creating closures inside a loop with var, so every callback sees the final loop value instead of its iteration's value (use let).
  • Capturing a huge object in a closure that lives for the lifetime of the page, a quiet memory leak.
  • Assuming a stale closure in React is broken; it is by design and useRef or the dependency array is the fix.
  • Treating closures as snapshots, they read the current value of the captured variable, not the value at capture time.
FAQ

Closure, Frequently Asked

Are closures unique to JavaScript?

No. Closures exist in most modern languages: Python, Ruby, Swift, Rust, Go, Scala, Lisp. JavaScript is just one of the most well-known examples because functional patterns dominate the language.

Do closures leak memory?

They can. If a closure outlives the scope that created it and still references large data, the garbage collector cannot reclaim that memory. Detach long-lived listeners and clear refs when no longer needed.

Why does a counter using let inside a loop work but var does not?

var is function-scoped, so every iteration shares the same binding. let is block-scoped, each iteration gets a fresh binding, so each closure captures its own value.

Related Terms