What is a closure in JavaScript? Provide an example.
Ask by Ravi Vishwakarma
Updated 23 Jun 2024
A 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:
outerFunctiondeclares a variableouterVariableand defines aninnerFunction.innerFunctionhas access toouterVariablebecause it is within the scope ofouterFunction.outerFunctionis called, it returnsinnerFunction. TheinnerFunctionmaintains access toouterVariableeven afterouterFunctionhas completed execution.closure()(which is the returnedinnerFunction) logs the value ofouterVariable.Practical Example :
Output: