DEV Community

Hemant Govekar
Hemant Govekar

Posted on

Closures in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

🔹 Explanation:

  • outerFunction() defines a local variable (counter).
  • innerFunction() modifies counter, but the outer function has already executed!
  • However, innerFunction() retains access to counter due to closure behavior.
  • Each call to increment() updates the retained counter, demonstrating persistent state.

Closures are useful for encapsulation, maintaining private variables, and creating efficient event handlers. 🚀

Top comments (6)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Closures in JavaScript occur when a function retains access to variables from its lexical scope,...

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.

 
hemantgovekar profile image
Hemant Govekar

Some comments may only be visible to logged-in visitors. Sign in to view all comments.