Closures in JavaScript
What is a Closure?
A closure is a feature in JavaScript where an inner function has access to variables from its outer (enclosing) function scope even after the outer function has returned.
Closure Can Access:
- Its own variables
- Outer function’s variables
- Global variables
Syntax Example:
function outerFunction() {
let outerVariable = "I'm outside!";
function innerFunction() {
console.log(outerVariable); // Access outerVariable
}
return innerFunction;
}
const closureFunc = outerFunction();
closureFunc(); // Output: I'm outside!
Even though outerFunction has finished running, innerFunction remembers outerVariable. This is a closure.
Real-Life Use Case: Counter
function createCounter() {
let count = 0;
return function () {
count++;
console.log("Count:", count);
};
}
const counter = createCounter();
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
- count is a private variable.
- It's not accessible directly, but the inner function can update and access it.
Closures Provide:
- Data encapsulation
- Private variables
- Persistent state across function calls
Closure in a Loop (With let)
for (let i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i); // Outputs: 0, 1, 2
}, 1000);
}
If you used var, all would log 3. But let creates a closure per iteration.
Common Interview Example
function greet(name) {
return function(message) {
console.log(`${message}, ${name}`);
};
}
const sayHelloToJohn = greet("John");
sayHelloToJohn("Hello"); // Output: Hello, John
Summary
Concept | Explanation |
---|---|
Closure | Function "remembers" the environment where it was created |
Uses | Data privacy, state persistence, callbacks |
Key Benefit | Avoid polluting global scope |