π What is a Closure?
A closure is a function that remembers the variables from its lexical scope even when the function is executed outside of that scope.
In simpler terms:
Closures allow a function to access variables from an outer function, even after that outer function has finished executing.
π Why Use Closures?
- Closures are useful when you want to:
- Preserve state across function calls
- Encapsulate variables (data hiding / private variables)
- Create function factories
- Avoid polluting the global scope
π‘ Simple Closure Example
π Closures as Private Variables
Letβs create a function that locks variables from the outside world:
π Function Factory with Closures
β οΈ Common Mistake
People often expect each loop iteration to have a fresh value:
π§ Closure Summary
π― Real-World Applications of Closures
Private methods in JavaScript classes
Maintaining state in React hooks like useState
Functional programming patterns
β Conclusion
Closures are one of the most powerful and misunderstood features in JavaScript. Mastering them will unlock a whole new level of confidence in writing secure, modular, and elegant code.
βοΈ Written By
Chaitanya Chopde
π Inspired By
@devsyncin
Top comments (5)
Interesting to read
Closures are my go-to for stateful patterns, especially in React hooks. What's your favorite closure use case outside of React?
Yes a favorite closure use case outside React: data privacy in JavaScript modules β like creating private counters or configs without exposing variables globally.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.