How do JavaScript closures work?
JavaScript closures are a feature of the language that allows inner functions to have access to variables and parameters defined in their parent function’s scope, even after the parent function has completed execution. This is achieved by creating a closure, which is an inner function that has access to the variables in the outer function’s scope.
When a function is defined within another function, the inner function has access to the variables defined in the outer function’s scope, and those variables are not garbage collected when the outer function completes execution. Instead, they are retained and can be accessed by the inner function when it is invoked.
Here is an example of a JavaScript closure:
function outerFunction(x) {
var innerVar = "I am an inner variable";
function innerFunction() {
console.log(x + " and " + innerVar);
}
return innerFunction;
}
var closure = outerFunction(10);
closure();
// Output: 10 and I am an inner variable
In the above example, when we call outerFunction(10)
, the inner function innerFunction()
gets returned, this inner function has access to the variable innerVar
and parameter x
even though the outer function has completed its execution. We can use the returned function closure
to access the variable and parameter.
Closures are useful for creating private variables and methods, which can only be accessed by the inner function and are hidden from the outside scope. They also allow for creating function factories, where a function returns a new function with different behavior based on the arguments passed to it.