- Scope Chain: When a function is defined within another function, it forms a nested scope. This nested function has access to its own variables and parameters as well as to variables in its containing (outer) function.
- Lifetime of Variables: Normally, when a function completes execution, its local variables are destroyed. However, if a nested function maintains a reference to those variables (through a closure), they remain accessible even after the outer function finishes execution.
- Creating a Closure: In the example above, when outerFunction is invoked and innerFunction is returned, a closure is created. The innerFunction retains access to outerVariable, even though outerFunction has finished executing.
- Accessing Outer Variables: When closureFunction is called, it executes innerFunction, which still has access to outerVariable, resulting in the value being logged to the console.
Closures are powerful for maintaining data privacy, creating factory functions, implementing modules, and managing asynchronous operations. They allow functions to encapsulate data and behavior, leading to more modular and maintainable code.