Closures in JavaScript
A closure is created when a function is defined inside another function and gains access to the outer function’s variables — even after the outer function has finished execution.
Key points:
-
The inner function 'remembers' the environment (variables) in which it was created.
-
Closures enable private variables — variables that cannot be accessed from outside the function directly.
Simple Example:
Even though outerFunction has finished running, closureFunc still remembers privateVariable.
Real-world use case: Private Counters
Here, count is private — it can only be modified using increment and decrement.