JavaScript Closures - Detailed Notes & Interview
Questions
1. Why Closures Exist
Normally, variables inside a function disappear when the function finishes.
Closures are the exception to this rule.
2. Basic Example
function A() {
let x = 10;
function B() {
[Link](x);
}
return B;
}
const result = A();
result();
Output:
10
Reason:
B remembers x even after A has finished.
3. Closure Definition
Interview Definition:
A closure is created when an inner function remembers and can access variables from its outer
function even after the outer function has finished execution.
4. The Counter Example
function counter() {
let count = 0;
return function() {
count++;
[Link](count);
};
}
const c = counter();
c();
c();
c();
Output:
1
2
3
Reason:
counter() executes only once.
The returned function keeps access to the same count variable.
5. Common Beginner Mistake
Many people think count becomes 0 again every time c() is called.
Wrong.
Only counter() creates count.
c() only uses the already existing count.
6. Why counter() Does Not Run Again
const c = counter();
This line runs counter() once.
The returned function is stored in c.
Later:
c();
calls only the returned function.
It does NOT call counter() again.
7. Proof Example
function counter() {
[Link]("counter ran");
let count = 0;
return function() {
count++;
[Link](count);
};
}
const c = counter();
c();
c();
c();
Output:
counter ran
1
2
3
Notice:
'counter ran' appears only once.
8. Multiple Counters
function counter() {
let count = 0;
return function() {
count++;
[Link](count);
};
}
const c1 = counter();
const c2 = counter();
c1();
c1();
c2();
c1();
Output:
1
2
1
3
Reason:
c1 and c2 each get their own separate count variable.
9. Private Variables
Closures are often used to create private variables.
Example:
function bank() {
let balance = 1000;
return function() {
[Link](balance);
};
}
The outside world cannot directly access balance.
10. Interview Keywords
Remember these keywords:
Inner Function
Outer Function
Lexical Scope
Remembering Variables
Private Variables
Data Hiding
Persistent State
Most Asked Interview Questions
Q1)
What is a closure?
Answer:
An inner function remembering variables of its outer function after the outer function has finished.
Q2)
Why do we use closures?
Answer:
Data hiding, private variables, persistent state, callbacks and event handlers.
Q3)
Predict Output
function A() {
let x = 10;
return function() {
[Link](x);
};
}
const f = A();
f();
Output:
10
Q4)
Predict Output
function counter() {
let count = 0;
return function() {
count++;
[Link](count);
};
}
const c = counter();
c();
c();
c();
Output:
1
2
3
Q5)
Predict Output
const c1 = counter();
const c2 = counter();
c1();
c1();
c2();
c1();
Output:
1
2
1
3
Q6)
Why doesn't count reset to 0?
Answer:
Because counter() ran only once. The returned function keeps a reference to the same count variable t