A closure is a function that remembers the variables from its outer scope even after the function execution is complete.
Closures allow functions to access variables outside their local scope. This is useful for data encapsulation and maintaining state across function calls.
For example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
};
}
const newFunction = outerFunction("Hello");
newFunction("World"); // Output: Outer: Hello, Inner: World
The innerFunction
still remembers outerVariable
even after outerFunction
has executed, demonstrating closure behavior.