Skip to content

Closures

A closure is created when an inner function remembers the variables from its outer environment, even after the outer function has finished executing.

In simple terms:

“A closure is a function that remembers where it was created.”


A closure can be used to create a timer that keeps track of the number of seconds elapsed.

function startTimer() {
let seconds = 0;
return function() {
seconds++;
console.log("Elapsed time:", seconds, "s");
};
}
const timer = startTimer();
timer(); // Elapsed time: 1 s
timer(); // Elapsed time: 2 s
timer(); // Elapsed time: 3 s

  • Preserve state across multiple calls (e.g. counter, timer).
  • Create private variables not accessible from the outside.
  • Avoid global variables → better encapsulation.
  • Very useful in callbacks and functional programming.

A closure can protect sensitive data (like a bank account balance) by making it accessible only through dedicated methods.

function createBankAccount() {
let balance = 0; // private variable
return {
deposit(amount) {
balance += amount;
console.log("New balance:", balance);
},
withdraw(amount) {
if (amount <= balance) {
balance -= amount;
console.log("Withdrawal successful, balance:", balance);
} else {
console.log("Insufficient funds");
}
}
};
}
const account = createBankAccount();
account.deposit(100); // New balance: 100
account.withdraw(30); // Withdrawal successful, balance: 70
// console.log(account.balance); ❌ not directly accessible

  • Too many unnecessary closures can consume memory.
  • They can create hidden references that prevent the garbage collector from freeing variables.
  • Used wisely, they make code safer and better structured.

A closure = a function + its environment.
It’s one of the pillars of modern JavaScript (used in callbacks, arrow functions, frameworks like React, etc.).