What is a Closure?
A closure is created when a function remembers variables from its outer lexical scope.
Master lexical scope, persistent state, private variables, and one of JavaScript's most powerful concepts.
Understand how functions remember variables from their outer scope even after execution has completed.
A closure is created when a function remembers variables from its outer lexical scope.
Inner functions can access parent variables because scope is determined by where code is written.
Closures enable state persistence, encapsulation, private variables, factory functions, and React hooks.
Call the returned inner function and watch it keep access to count after outer() has already completed.
1function outer() {2let count = 0;34return function inner() {5count++;6return count;7};8}910const counter = outer();1112counter();13counter();14counter();
Animated memory box
0
outer() finished, but counter still points to inner(). Because inner() references count, JavaScript keeps that lexical environment alive.
Test lexical scope, persistent state, memory risk, and React closure behavior.
Detailed answers for the closure questions that show up in frontend and full-stack interviews.
A closure is created when a function keeps access to variables from its outer lexical scope after that outer function has finished executing. The function carries its surrounding environment with it.
Lexical scope means variable access is determined by where functions are written in the source code. Inner functions can read variables from parent scopes because of their placement in the code.
When an inner function references outer variables, JavaScript preserves the referenced lexical environment. If the inner function is returned or stored, that environment remains alive for future calls.
Yes. If a closure is kept alive by an event listener, cache, timer, or global reference, anything it references may stay in memory. Clean up listeners and avoid capturing large unused objects.
React callbacks, effects, memoized functions, and custom hooks all use closures. They capture props, state, and helper functions from the render where they were created, which is why dependency arrays matter.