A closure in JavaScript is the combination of a function bundled together with references to its surrounding state, known as the lexical environment. In simpler terms, a closure allows an inner function to remember and access variables from its outer (parent) function's scope, even after the outer function has completely finished executing.
- Every time a function is created in JavaScript, a closure is automatically created alongside it.
Why is Closure Used?
Preserve data between function calls
Create private variables
Avoid polluting the global scope
Implement function factories
Maintain state in asynchronous operations
Example
function bankAccount() {
let balance = 1000;
return {
deposit(amount) {
balance += amount;
console.log(`Balance: ${balance}`);
},
withdraw(amount) {
balance -= amount;
console.log(`Balance: ${balance}`);
},
getbalance(){
console.log("Balance: ",balance);
}
};
}
const account = bankAccount();
account.deposit(500); // Balance: 1500
account.withdraw(200); // Balance: 1300
console.log(account.balance); //undefined (it is a private variable)
account.getbalance(); // Balance: 1300
Output
Balance: 1500
Balance: 1300
undefined
Balance: 1300
Advantages of Closures
1. Data Privacy
Variables can be hidden from outside access.
function secret() {
let password = "1234";
return function () {
console.log(password);
};
}
2. Maintain State
A function can remember previous values.
function createCounter() {
let count = 0;
return function () {
return ++count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
3. Avoid Global Variables
Without closure:
let count = 0;
With closure:
function counter() {
let count = 0;
}
Keeps variables local and prevents accidental modification.
4. Function Factories
Closures can generate customized functions.
function multiplyBy(num) {
return function (value) {
return value * num;
};
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
Here, each returned function remembers its own num.
Closure means a function "remembers" the variables of its parent function even after the parent function has completed execution.
Closures provide
Access to parent scope variables.
Variables remain alive after the parent function ends.
Data privacy (private variables).
State management.
Less use of global variables.
Function factories.
Useful for callbacks, timers, and event handlers.
Lexical Scoping
Closures rely on lexical scoping, which means a functionโs scope is determined by where it is defined, not where it is executed.
A function retains access to the scope where it was defined.
Inner functions can access outer function variables.
Enables closures to โrememberโ their environment.
A closure is a function that remembers and accesses variables from its outer scope even after the outer function has finished executing, enabling data privacy, state preservation, and function customization.
References
https://www.w3schools.com/js/js_function_closures.asp
https://www.geeksforgeeks.org/javascript/closure-in-javascript/
Top comments (0)