🔥 Closure = “private variables” in JavaScript (without classes). This is a very common interview pattern, and it shows you really understand closures. ❓ What’s the output? A) 1,2,1,2,1 B) 1,2,1,2,2 C) 1,2,1,1,1 D) Throws an error ❓Why can’t we access the count directly from outside? 📈 Real-world relevance: This is the core idea behind “instance state”: keep it private without exposing it globally. 💬 Drop your answers + reasoning 👇 #CodeSnatch #javascript #closures #interviewprep #webdevelopment #frontend #codinginterviews
Mini interview follow-up (extra spicy 🌶️) const { inc } = createCounter(); console.log(inc()) ❓Does it still work? Why?
count is private, and the returned methods are the public API. So basically, a.inc() and b.inc() are two separate closures!
✅ Correct answer: A) 1, 2, 1, 2, 1 a.inc() → a.count goes 0 → 1 → prints 1 a.inc() → 1 → 2 → prints 2 b.inc() → b is a separate closure, its count goes 0 → 1 → prints 1 a.get() → returns a’s count which is 2 b.get() → returns b’s count which is 1