Closures in JavaScript occur when a function retains access to variables from its lexical scope, even after the outer function has finished execution. This allows functions to "remember" values and maintain state.
πΉ Simple Example:
function outerFunction() { let counter = 0; // Local variable return function innerFunction() { counter++; // Inner function remembers 'counter' console.log(counter); }; } const increment = outerFunction(); // Returns innerFunction increment(); // 1 increment(); // 2 increment(); // 3 πΉ Explanation:
-
outerFunction()defines a local variable (counter). -
innerFunction()modifiescounter, but the outer function has already executed! - However,
innerFunction()retains access tocounterdue to closure behavior. - Each call to
increment()updates the retainedcounter, demonstrating persistent state.
Closures are useful for encapsulation, maintaining private variables, and creating efficient event handlers. π
Top comments (6)
In other words, a closure is created every time any function is created - since ALL functions retain access to their lexical scope. Every function has an associated closure.
X id: @hemantgovekar
Some comments may only be visible to logged-in visitors. Sign in to view all comments.