What is a Closure in JavaScript?
Learn what a closure is in JavaScript, how the scope chain keeps variables alive, private counter examples, and common closure interview questions.
Expected Interview Answer
A closure is a function that retains access to variables from its enclosing lexical scope even after that outer function has finished executing. This lets inner functions remember and manipulate state from where they were created, not from where they are called.
When a function is defined inside another function, it forms a closure over the outer function's variables through the scope chain established at creation time. JavaScript keeps those referenced variables alive in memory as long as the inner function still exists somewhere, rather than garbage collecting them when the outer function returns. This is the mechanism behind common patterns like private counters, memoization caches, and factory functions that produce customized behavior. Each call to the outer function creates a fresh, independent closure, so multiple instances do not share state unless intentionally designed to.
- Enables data privacy without classes
- Powers factory functions and function currying
- Backbone of memoization and caching patterns
- Preserves state across asynchronous callbacks
- Key mechanism behind React hooks and event handlers
AI Mentor Explanation
A closure is like a bowler who remembers the exact field placement set by the captain earlier in the over, even after the captain has walked back to the pavilion. Every delivery the bowler sends down still references that same field map, not a fresh one recalculated from scratch. Two different bowlers given field settings from separate overs each carry their own private memory of it.
Closure scope chain: inner function retaining access to outer variables
Outer function call
- Creates a variable environment
- Defines and returns inner function
Inner function (closure)
- References outer variable via scope chain
- Keeps outer variable alive after outer returns
Each invocation
- Produces an independent closure
- Own private copy of outer variables
Step-by-Step Explanation
Step 1
Define nested function
An inner function is declared inside an outer function, forming a lexical link to the outer scope.
Step 2
Outer function returns
The outer function finishes execution and would normally have its local variables discarded.
Step 3
Scope chain keeps variables alive
Because the inner function still references those variables, the engine keeps them in memory instead of garbage collecting them.
Step 4
Inner function is called later
Whenever the returned inner function runs, it still reads and updates the original outer variables.
Step 5
Independent closures per call
Each separate invocation of the outer function creates its own private closure with its own variable copies.
What Interviewer Expects
- Defines closure as function plus its lexical environment
- Can build a counter or private-state example live
- Explains why each call creates an independent closure
- Connects closures to memory retention and the scope chain
- Names real use cases like memoization or event handler state
Common Mistakes
- Saying closures only matter for private variables
- Believing all closures share the same outer state
- Confusing closures with plain nested functions with no captured state
- Forgetting closures can cause memory leaks if not managed
- Not knowing closures capture variables by reference, not by value
Best Answer (HR Friendly)
“A closure is a function that remembers the data from where it was created, even after that outer code has finished running. It's a core JavaScript feature used to create private variables and functions that keep their own memory, like a counter that keeps track of its count.”
Code Example
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
console.log(counterA()); // 1
console.log(counterA()); // 2
console.log(counterB()); // 1 (independent closure)Follow-up Questions
- How do closures enable data privacy in JavaScript?
- Can closures cause memory leaks, and how do you avoid them?
- How does the classic 'var in a loop' closure bug happen?
- What is the difference between a closure and the scope chain?
- How do React hooks like useState rely on closures?
MCQ Practice
1. What does a closure allow a function to do?
A closure lets an inner function retain access to outer variables even after the outer function has finished executing.
2. If makeCounter() is called twice, do the two counters share state?
Each invocation of the outer function creates a new variable environment, so the returned closures are independent.
3. What keeps a closed-over variable alive after the outer function returns?
The inner function retains a reference to the outer variable through the scope chain, preventing garbage collection.
Flash Cards
Define a closure. — A function bundled with references to its surrounding lexical scope, retained even after the outer function returns.
Why don't multiple counters from the same factory share state? — Each call to the outer function creates its own independent variable environment and closure.
What common bug do closures cause in loops with var? — All callbacks share the same var binding, so they all see the final loop value instead of their own.
Name one practical use of closures. — Creating private state, such as a counter or cache, without needing a class.