What is closure in JavaScript?
In JavaScript, a closure is created when a function is defined inside another function. The inner function has access to the outer function's variables and parameters, even after the outer function has returned.
This happens because the inner function "closes over" the variables and parameters of the outer function, creating a persistent scope chain that remains in memory even after the outer function has been completed.
Here's an example of a closure:
function outerFunction(x) {
function innerFunction(y) {
return x + y;
}
return innerFunction;
}
var add5 = outerFunction(5);
console.log(add5(3)); // Output: 8
In this example, outerFunction returns innerFunction, which has access to the x parameter of the outer function. The returned function is assigned to the variable add5, which can now be called with a value for y.
Even though outerFunction has completed and returned, the closure created by innerFunction still has access to the value of x, because it "closes over" the parameter of the outer function.
Closures are useful in many programming situations, such as creating private variables and functions, implementing callbacks and event handlers, and reducing global namespace pollution.