Closures are a powerful feature in functional programming where a function remembers and continues to access variables from its enclosing scope, even after the outer function has finished executing.
Let’s consider an example:
function counter(step = 1) {
let count = 0;
return function increaseCount() {
count += step;
return count;
}
}
const incBy1 = counter();
const incBy10 = counter(10);
console.log(incBy1()); // Output: 1
console.log(incBy1()); // Output: 2
console.log(incBy10()); // Output: 10
console.log(incBy10()); // Output: 20
In this scenario, the inner function increaseCount
forms a closure. It captures and utilizes the count
and step
variables from its parent function’s scope, maintaining their state between function calls.
Closures are essential for:
For more insight, resources like MDN’s closure documentation and articles like “JavaScript Closures Explained by Mailing a Package” from freeCodeCamp can provide additional examples and explanations.