A closure is a function that remembers variables from its outer function, even after the outer function has finished executing.
A closure is created when an inner function remembers and accesses variables from its outer scope.
Example:
function outer() {
let name = "Sathish";
function inner() {
console.log(name);
}
inner();
}
outer();
Output:
Sathish
Explanation:
- outer() creates a variable called name.
- inner() accesses the name variable from the outer function.
- When inner() runs, it prints "Sathish". This demonstrates closure-related scope behavior. Let's see the more important example below, where the inner function is used after the outer function finishes.
Important closure Example:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
let result = outer();
result();
result();
result();
Output:
1
2
3
Why do we use closures?
- To preserve variables between function calls.
- To create private variables.
- To maintain state in JavaScript.
- To build counters and callbacks.
Top comments (0)