JavaScript Closure Definition and Use Cases

🎯 Mock Interview Question of the Day: What is Closure in JavaScript? Today in my mock interview, I was asked: 👉 What is a closure? 👉 Why is it used? 👉 How does it work? Here’s how I answered 👇 ✅ What is Closure? A closure is when an inner function remembers and can access variables from its outer function even after the outer function has finished executing. In simple words: A function “closes over” its surrounding variables. ✅ Why Do We Use Closure? Closures are mainly used for: ✔ Data hiding / private variables ✔ Maintaining state ✔ Creating function factories ✔ Callbacks and event handlers ✔ Implementing module patterns Closures help in writing secure and optimized JavaScript code. ✅ How Does It Work? function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 🔎 Explanation: outer() executes and returns inner Normally, local variables disappear after execution But since inner() uses count, JavaScript keeps it in memory This preserved scope is called a closure 💡 Interview Tip: Whenever asked about closure, always explain: Definition Real-life use case Code example Memory concept (lexical scope) Practicing mock interviews daily to strengthen my JavaScript fundamentals 🚀 #MockInterview #JavaScript #FrontendDeveloper #MERNStack #LearningInPublic #WebDevelopment

To view or add a comment, sign in

Explore content categories