Free Online Code Editor
Understand and use closures for data privacy.
// Basic closure
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
// Private variables
function createBankAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
if (amount > balance) {
throw new Error("Insufficient funds");
}
balance -= amount;
return balance;
},
getBalance() {
return balance;
}
};
}
const account = createBankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
// console.log(account.balance); // undefined (private)
// Closure in loops
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 0, 1, 2 (let creates new scope each iteration)
// With var (old behavior)
for (var j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 100);
}
// Output: 3, 3, 3 (var is function-scoped)
// IIFE with closure
const module = (function() {
let privateVar = "secret";
return {
getSecret() {
return privateVar;
},
setSecret(value) {
privateVar = value;
}
};
})();
console.log(module.getSecret());
module.setSecret("new secret");
// Memoization with closure
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
};
}
const expensiveCalc = memoize((n) => {
console.log("Calculating...");
return n * 2;
});
console.log(expensiveCalc(5)); // Calculates
console.log(expensiveCalc(5)); // Cached
// Partial application
function multiply(a) {
return function(b) {
return a * b;
};
}
const double = multiply(2);
const triple = multiply(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15Closures remember their outer scope. Use for data privacy, memoization, partial application. Inner function has access to outer variables even after outer returns.