Closures
What is a closure?
Section titled “What is a closure?”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.”
Concrete example: timer
Section titled “Concrete example: timer”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 stimer(); // Elapsed time: 2 stimer(); // Elapsed time: 3 s
Practical uses of closures
Section titled “Practical uses of closures”- 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.
Example: private variables
Section titled “Example: private variables”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: 100account.withdraw(30); // Withdrawal successful, balance: 70// console.log(account.balance); ❌ not directly accessible
Pitfalls to know
Section titled “Pitfalls to know”- 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.
Summary
Section titled “Summary”A closure = a function + its environment.
It’s one of the pillars of modern JavaScript (used in callbacks, arrow functions, frameworks like React, etc.).