Mahmoud Abdalrahman’s Post

POST 2 — Closures Are Not a Trick Question. They're the Foundation. 🔒 Closures come up in every JavaScript interview. Most developers memorize a definition. Very few understand what's actually happening in memory. Here's the real explanation 👇 ───────────────────────── What a closure actually is: When a function is created in JavaScript, it doesn't just capture its own code. It captures a reference to the ENVIRONMENT it was created in — every variable that was in scope at the moment of creation. That environment stays alive in memory as long as the function exists. Even after the outer function has finished executing and returned. ───────────────────────── Why this matters more than the interview answer: Every function in JavaScript is a closure. Not just the tricky nested ones from coding challenges. Every callback. Every event handler. Every composable. They all close over the scope they were created in. Understanding closures means understanding why your event handler still references an old value, why your loop callbacks all print the same number, and why your module pattern works at all. ───────────────────────── The memory angle nobody teaches: Closures keep variables alive. If a closure references a large object, that object cannot be garbage collected for as long as the closure exists. Event listeners attached to long-lived DOM elements hold closures. Those closures hold references. Those references hold memory. This is one of the most common sources of memory leaks in frontend applications — and it's invisible unless you know what to look for. ───────────────────────── The stale closure bug: In Vue composables, closures captured at render time hold the values from THAT render. If you read state inside a setTimeout or an event handler without accounting for this, you will read stale values. The fix is not to avoid closures. It's to understand when your closure was created and what environment it captured. ───────────────────────── One sentence that makes closures click: A closure is a function that remembers the world it was born into — even after that world is gone. ───────────────────────── What was the closure bug that taught you this the hard way? Tell me in the comments 👇 #JavaScript #WebDevelopment #Programming #FrontendDevelopment #WebDev

To view or add a comment, sign in

Explore content categories