What is Closure in JavaScript?
In JavaScript, a closure is a combination of a function and the lexical environment within which that function was declared.
In JavaScript, a closure is a combination of a function and the lexical environment within which that function was declared. It allows a function to retain access to variables and parameters of its outer (enclosing) function, even after the outer function has finished executing.
A closure is created whenever an inner function references variables or parameters from its outer function. The inner function has access to its own local variables, the variables and parameters of the outer function, and also the global variables.
Here's an example to illustrate closures in JavaScript:
In the above example, the outerFunction
defines an inner function called innerFunction
. The innerFunction
references the outerVariable
defined in its enclosing outerFunction
. When the outerFunction
is called and assigned to the variable closure
, it returns the innerFunction
itself. So, closure
now becomes a reference to the innerFunction
, which still has access to the outerVariable
even after the outerFunction
has completed execution. When closure
is invoked, it prints the value of outerVariable
.
Closures are powerful because they allow functions to have private variables and create a form of data encapsulation. They are commonly used in scenarios such as creating private variables, implementing modules, and maintaining state in asynchronous operations.