DEV Community

Cover image for πŸ“– Closures in JavaScript β€” Unlocking Private Variables
Chaitanya Chopde
Chaitanya Chopde

Posted on

πŸ“– Closures in JavaScript β€” Unlocking Private Variables

πŸ” 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?

  1. Closures are useful when you want to:
  2. Preserve state across function calls
  3. Encapsulate variables (data hiding / private variables)
  4. Create function factories
  5. Avoid polluting the global scope

πŸ’‘ Simple Closure Example

Image description

πŸ” Closures as Private Variables

Let’s create a function that locks variables from the outside world:

Image description

🏭 Function Factory with Closures

Image description

⚠️ Common Mistake

People often expect each loop iteration to have a fresh value:

Image description

🧠 Closure Summary

Image description

🎯 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 (4)

Collapse
 
dotallio profile image
Dotallio

Closures are my go-to for stateful patterns, especially in React hooks. What's your favorite closure use case outside of React?

Collapse
 
chaitanya_chopde_dd0642ed profile image
Chaitanya Chopde

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.