What is a Closure?
A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing.
function createGreeter(greeting) {
return function(name) {
console.log(greeting + ", " + name + "!");
};
}
const sayHello = createGreeter("Hello");
const sayHi = createGreeter("Hi");
sayHello("Alice"); // Hello, Alice!
sayHi("Bob"); // Hi, Bob!
Try it Yourself โ
Closure for Private Variables
Closures enable data privacy by keeping variables inaccessible from the outside.
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.getCount()); // 2
// console.log(counter.count); // undefined
Closures in Loops
Classic closure pitfall: using var in a loop creates shared scope. Use let or an IIFE to fix it.
for (let i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i); // 0, 1, 2 (with let)
}, 100);
}
Practical Closure: Function Factory
Closures are great for creating specialized functions from a common template.
function multiplyBy(factor) {
return function(n) {
return n * factor;
};
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(10)); // 20
console.log(triple(10)); // 30
Closures in Event Handlers
Closures let event handlers capture state at the time of registration.
function setupButtons() {
for (let i = 0; i < 5; i++) {
const btn = document.createElement("button");
btn.textContent = "Button " + i;
btn.onclick = function() {
console.log("Clicked button " + i);
};
document.body.appendChild(btn);
}
}