| Functions, Parameters & Scope in JavaScript | Javascript Word Counter | |
Closures in JavaScript |
Closures are one of the most powerful (and tricky!) concepts in JavaScript. Let’s break it down step by step with a practical example you can actually use.
A closure is created when an inner function “remembers” the variables from its outer function’s scope, even after the outer function has finished executing.
function outer() {
let counter = 0; // outer variable
function inner() {
counter++; // inner function uses outer variable
return counter;
}
return inner;
}
const increment = outer(); // outer() returns inner function
console.log(increment()); // 1
console.log(increment()); // 2
console.log(increment()); // 3
👉 Here, increment “remembers” the variable counter from outer(),
even though outer() has already finished running.
Closures are often used to create private variables that cannot be accessed directly from outside.
function bankAccount(initialBalance) {
let balance = initialBalance; // private variable
return {
deposit: function(amount) {
balance += amount;
console.log(`Deposited: ${amount}, Balance: ${balance}`);
},
withdraw: function(amount) {
if (amount <= balance) {
balance -= amount;
console.log(`Withdrew: ${amount}, Balance: ${balance}`);
} else {
console.log("Insufficient funds!");
}
},
getBalance: function() {
return balance;
}
};
}
const myAccount = bankAccount(1000);
myAccount.deposit(500); // Deposited: 500, Balance: 1500
myAccount.withdraw(200); // Withdrew: 200, Balance: 1300
console.log(myAccount.getBalance()); // 1300
// ❌ Direct access not possible
// console.log(myAccount.balance); // undefined
👉 In short: Closures = Function + Remembered Environment. They let you “carry around” variables with a function, which is why they’re so powerful.
function setupButton() {
let clickCount = 0;
document.getElementById("myBtn").onclick = function() {
clickCount++;
console.log("Button clicked " + clickCount + " times");
};
}
setupButton();
function bankAccount(initialBalance) {
let balance = initialBalance;
return {
deposit: function(amount) { balance += amount; },
withdraw: function(amount) { balance -= amount; },
getBalance: function() { return balance; }
};
}
const account = bankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
account.withdraw(30);
console.log(account.getBalance()); // 120
function delayedMessage(msg, delay) {
setTimeout(function() {
console.log("Message: " + msg);
}, delay);
}
delayedMessage("Hello after 2s", 2000);
| Functions, Parameters & Scope in JavaScript | Javascript Word Counter | |