JavaScriptApril 11, 2026
JavaScript Closures: A Deep Dive
Master JavaScript closures to write more powerful and flexible code.
Closures are one of the most powerful features in JavaScript. Let’s understand them thoroughly.
What is a Closure?
A closure is a function that has access to variables from its outer (enclosing) scope, even after that scope has finished executing.
javascript
function createCounter() {
let count = 0 // Private variable
return {
increment() {
count++
return count
},
decrement() {
count--
return count
},
getCount() {
return count
}
}
}
const counter = createCounter()
counter.increment() // 1
counter.increment() // 2
counter.getCount() // 2
Practical Use Cases
Data Privacy
javascript
function createBankAccount(initialBalance) {
let balance = initialBalance
return {
deposit(amount) {
balance += amount
return balance
},
withdraw(amount) {
if (amount <= balance) {
balance -= amount
return balance
}
throw new Error('Insufficient funds')
},
getBalance() {
return balance
}
}
}
Function Factories
javascript
function createMultiplier(multiplier) {
return function(number) {
return number * multiplier
}
}
const double = createMultiplier(2)
const triple = createMultiplier(3)
double(5) // 10
triple(5) // 15
Common Pitfalls
Loop Variable Capture
javascript
// Problem
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100)
}
// Outputs: 3, 3, 3
// Solution: Use let
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100)
}
// Outputs: 0, 1, 2