Learn what closures are in JavaScript, how they work, and see clear examples that make closures easy, even for beginners. Perfect for web developers!
Table of content
Closures are a fundamental JavaScript concept that every web developer encounters, often without realizing it. Simply put, a closure gives an inner function access to the variables of an outer function—even after the outer function has finished executing.
Whenever you create a function inside another function, the inner function forms a closure. It “remembers” the scope in which it was created, including any variables and parameters from the outer function.
function outer() {
let message = 'Hello from outer!';
function inner() {
console.log(message); // 'Hello from outer!'
}
return inner;
}
const myClosure = outer();
myClosure(); // Outputs: 'Hello from outer!'
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2
Closures are used in factory functions to create new functions with specific behaviors.
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // 10
let
and const
to avoid variable hoisting issues.let
in the loop header if needed.Closures in JavaScript might seem tricky at first, but understanding them unlocks powerful programming techniques. Whether you’re building private variables or factories, closures help organize your code and create robust web applications.