Introduction
Closures let functions remember the environment where they were created. This helps keep data safe and create useful tools.
Closures let functions remember the environment where they were created. This helps keep data safe and create useful tools.
function outer() { let secret = 42; function inner() { console.log(secret); } return inner; }
function makeCounter() { let count = 0; return function() { count++; return count; }; } const counter = makeCounter(); console.log(counter()); // 1 console.log(counter()); // 2
function greet(name) { return function(message) { console.log(`${message}, ${name}!`); }; } const greetAlice = greet('Alice'); greetAlice('Hello'); // Hello, Alice!
function makeMultiplier(x) { return function(y) { return x * y; }; } const double = makeMultiplier(2); console.log(double(5)); // 10
This program uses closures to keep the bank account balance private. Only the returned methods can change or see the balance.
function createBankAccount(initialBalance) { let balance = initialBalance; return { deposit(amount) { balance += amount; console.log(`Deposited: $${amount}`); }, withdraw(amount) { if (amount <= balance) { balance -= amount; console.log(`Withdrew: $${amount}`); } else { console.log('Insufficient funds'); } }, getBalance() { return balance; } }; } const myAccount = createBankAccount(100); myAccount.deposit(50); myAccount.withdraw(30); console.log(`Balance: $${myAccount.getBalance()}`);
Closures help protect data by hiding it inside functions.
Be careful with closures inside loops to avoid unexpected results.
Closures can use more memory because they keep variables alive.
Closures let functions remember variables from where they were made.
They are useful for data privacy, creating special functions, and keeping state.
Closures are a powerful tool to write cleaner and safer code.
function makeAdder(x) {
return function(y) {
return x + y;
};
}
const add5 = makeAdder(5);
console.log(add5(3));function createFuncs() {
let funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(function() { return i; });
}
return funcs;
}
const functions = createFuncs();
console.log(functions[0]());function createFuncs() {
let funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(function() { return i; });
}
return funcs;
}
const functions = createFuncs();
console.log(functions[0](), functions[1](), functions[2]());Pass the test and this pattern moves unknown