Closure in Javascript
In JavaScript, a closure is a powerful concept that allows a function to retain access to variables from its lexical scope even after the function has finished executing. This means that the inner function has access to the variables and parameters of its outer function, even after the outer function has returned.
Key Characteristics of Closures
- Lexical Scope: Closures are based on the concept of lexical scoping. The scope of a variable is determined by its location in the source code. When a function is created, it captures the scope in which it was defined.
- Persistent State: Closures can be used to create functions with private variables, maintaining state between function calls without exposing the internal state.
How Closures Work
Here’s a basic example to illustrate how closures work:
function outerFunction() {
let outerVariable = 'I am from outer scope';
function innerFunction() {
console.log(outerVariable); // 'I am from outer scope'
}
return innerFunction;
}
const closureFunction = outerFunction();
closureFunction(); // Output: I am from outer scopeExplanation
- Function Creation:
outerFunctioncreates and returnsinnerFunction. - Returning the Inner Function:
innerFunctionretains access toouterVariableeven afterouterFunctionhas finished executing and returned. - Calling the Closure: When
closureFunctionis called, it still has access toouterVariable, demonstrating that the closure has preserved the environment in which it was created.
Get Roshanurkande’s stories in your inbox
Join Medium for free to get updates from this writer.
Practical Uses of Closures
- Encapsulation and Data Privacy: Closures can be used to create private variables and methods:
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2- In this example,
countis a private variable that can only be accessed and modified through the provided methods.
2. Function Factories: Closures can be used to create functions with specific configurations:
function makeMultiplier(multiplier) {
return function(value) {
return value * multiplier;
};
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15- Here,
makeMultipliercreates functions that multiply their input by a specific factor.
3. Event Handlers and Callbacks: Closures are often used in event handlers and asynchronous callbacks to maintain state:
function setupButton(buttonId) {
let clicks = 0;
document.getElementById(buttonId).addEventListener('click', function() {
clicks++;
console.log(`Button clicked ${clicks} times`);
});
}
setupButton('myButton');In this case, the click event handler retains access to the clicks variable, which tracks the number of clicks.
Summary
- Closures allow a function to access variables from its outer scope even after the outer function has finished executing.
- They are created whenever a function is defined within another function.
- Closures are useful for creating private variables, maintaining state, and managing function configurations.
Closures are a fundamental concept in JavaScript that provide powerful ways to manage and encapsulate state and behavior in your programs.





