Closure
A closure is created when an inner function remembers and can access the variables of its outer function even after the outer function has finished executing.
In simple words:
A closure allows a function to "remember" the environment in which it was created.
This is one of JavaScript's most powerful features and is commonly used for data privacy, maintaining state, callbacks, and event handling.
Why Do We Need Closures?
Normally, local variables exist only while a function is running.
Once the function finishes execution, its local variables are destroyed.
But sometimes we need those variables even after the function has finished.
Closures solve this problem by allowing the inner function to remember those variables.
Basic Example
function outer() {
let message = "Hello";
function inner() {
console.log(message);
}
return inner;
}
const greet = outer();
greet();
Output
Hello
Step-by-Step Execution
Step 1
outer() is called.
let message = "Hello";
A local variable is created.
Step 2
Inside outer(), another function is created.
function inner() {
console.log(message);
}
The inner() function can access message because it is inside outer().
Step 3
Instead of calling inner(), we return it.
return inner;
Step 4
The returned function is stored.
const greet = outer();
Although outer() has finished execution, JavaScript does not destroy the variable message.
Why?
Because the returned function still needs it.
Step 5
Now we call:
greet();
Output:
Hello
The inner function still remembers the variable.
This memory is called a closure.
Visual Representation
outer()
│
├── message = "Hello"
│
└── return inner()
│
▼
greet()
│
▼
console.log(message)
│
▼
"Hello"
Even though outer() has finished, message is still available because inner() remembers it.
Example 2: Counter
function counter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const increment = counter();
increment();
increment();
increment();
Output
1
2
3
How It Works
When counter() runs,
count = 0
The returned function remembers count.
Each time the function is called,
count++;
The value increases instead of resetting.
Without a closure, count would become 0 every time.
Example 3: Private Variable
function bankAccount() {
let balance = 5000;
return function () {
console.log(balance);
};
}
const checkBalance = bankAccount();
checkBalance();
Output
5000
The variable balance cannot be accessed directly.
console.log(balance);
Output
ReferenceError
Only the returned function can access it.
This provides data privacy.
Closure with Parameters
function multiply(x) {
return function(y) {
return x * y;
};
}
const double = multiply(2);
console.log(double(5));
Output
10
Here,
x = 2
is remembered by the returned function.
Later,
2 × 5 = 10
References:
https://www.geeksforgeeks.org/javascript/closure-in-javascript/
https://www.w3schools.com/js/js_function_closures.asp
Top comments (0)