Closures are a fundamental concept in JavaScript (and other programming languages) that refer to a function’s ability to “remember” and access its lexical scope, even when that function is executed outside of its original scope. Closures allow functions to access variables from their containing (enclosing) function’s scope, creating a powerful way to manage and encapsulate state.
Function Inside a Function
A closure occurs when a function is defined inside another function, and the inner function has access to the outer function’s variables.
Example
function createCounter() {
let counter = 0;
return function () {
return (counter += 1);
};
}
let runCounter = createCounter();
console.log(runCounter()); // 1
console.log(runCounter()); // 2
console.log(runCounter()); // 3
console.log(runCounter()); // 4
The createCounter()
function returns an anonymous function that, when called, increments counter
by 1 and returns the updated value. Each call to runCounter()
increments the counter by 1 and returns a new value.
Closures can be used to create function factories that generate multiple functions with different behaviors but share some common state.
Example
function multiplier(factor) {
return function (number) {
return number * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
The multiplier()
function takes a parameter factor and returns an anonymous function.
The returned function takes another parameter number
and returns the result of multiplying number
by factor
.