What is a closure in JavaScript? Provide an example.
243
17-Jun-2024
Updated on 23-Jun-2024
Ravi Vishwakarma
17-Jun-2024A closure in JavaScript is a feature where an inner function has access to its outer (enclosing) function's variables even after the outer function has finished executing. Closures are created whenever a function is created, allowing the function to remember the scope in which it was created.
Key Characteristics of Closures:
Example of a Closure:
In this example:
outerFunction
declares a variableouterVariable
and defines aninnerFunction
.innerFunction
has access toouterVariable
because it is within the scope ofouterFunction
.outerFunction
is called, it returnsinnerFunction
. TheinnerFunction
maintains access toouterVariable
even afterouterFunction
has completed execution.closure()
(which is the returnedinnerFunction
) logs the value ofouterVariable
.Practical Example :
Output: