What is a Closure:
A closure is a function that remembers the variables from its outer function even after the outer function has finished executing.
example:
function outer() {
let name = "Bala";
function inner() {
console.log(name);
}
return inner;
}
const myFunction = outer();
myFunction();
Output:
Bala
step by step Explanation:
1.outer() function runs
2.Variable name is created
3.inner() function is returned
4.Even after outer() finishes, inner() still remembers name
5.This is called closure
**Why Do We Use Closures in JavaScript**
- Data privacy *To remember values *To avoid global variables *To maintain state *For callbacks and timers
- Data Privacy (Real-World Example: Password):
We use closures to hide private data.
function createPassword() {
let password = "12345";
return function() {
console.log(password);
};
}
const getPassword = createPassword();
getPassword(); // 12345
Maintaining State (Real-World Example: Counter)
Closures help to remember previous value.
function counter() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
const c = counter();
c(); // 1
c(); // 2
c(); // 3
Used in setTimeout / Callbacks
function greet(name) {
setTimeout(function() {
console.log("Hello " + name);
}, 2000);
}
greet("Bala");
**How Closure Works (Lexical Scope)**
What is Lexical Scope
A function can access variables from its parent (outer) function based on where the function is written in the code.
simple:
* Inner function โ can access outer variables.
* Outer function โ cannot access inner variables.
Example : Lexical Scope?
function outer() {
let name = "Bala";
function inner() {
console.log(name);
}
inner();
}
outer();
Merits of Closures
*Data privacy
- State management *Avoid global variables *Used in callbacks *Used in real-world applications
Top comments (1)
Unfortunately, a closure is NOT a function and nesting functions is not required for their creation.
Misconceptions About Closures