JavaScript Closures Explained

🧸 Closure — Story First Imagine: 👉 A child goes outside to play 👉 But he still remembers what’s inside his house That’s a closure. 👉 A function goes outside its original scope 👉 But still remembers variables from where it was created 🧠 Real Definition:- A closure is a javascript feature where a function remembers and can access variables from its outer (lexical) scope even after the outer function has finished executing. ⚙️ Behind the Scenes (JS Engine) 💡 Example:- function outer() {  let count = 0;  return function inner() {   count++;   console.log(count);  }; } const counter = outer(); counter(); counter(); 📦 Step 1: Global Execution Context Created 1- Stored in Call Stack 2- Memory allocated: outer → function counter → undefined ⚙️ Step 2: outer() is called 👉 New Execution Context created for outer :- Inside its memory: count = 0 inner = function() {...} 👉 Normally, when outer() finishes → its memory should be deleted ❌ BUT… 👉 JavaScript sees: “inner function is still using count” So it does something special: 🔥 Closure is Created 👉 JS keeps count alive in memory 👉 Even after outer() is finished This saved memory is called: 👉 Lexical Environment ⚡ Step 3: Execution counter(); → 1 counter(); → 2 👉 Because count is remembered (not destroyed) 🧠 Where is this stored? 👉 The closure data is stored in: Execution Context memory Referenced via Scope Chain Internally kept in Heap (because it persists) (Heap is a region of memory where JavaScript stores reference types like objects, arrays, and functions.) 🔥 Why Closures Matter (Real World) Data privacy (private variables) React hooks Callbacks Event handlers #JavaScript #FrontendDeveloper #WebDevelopment #CodingJourney

To view or add a comment, sign in

Explore content categories