Understanding JavaScript Closures

🧠 JavaScript Closures — Explained in a Simple Way In JavaScript, a closure happens when a function remembers and can still use variables from the place where it was created — even after the outer function has finished. Think of it like having a key to a room. Even if the door is closed later… you can still enter and use the items inside. 🔑🚪 Here’s a quick example: function outer() { let message = "Hello 👋"; return function inner() { console.log(message); }; } const fn = outer(); fn(); // 👉 Output: Hello 👋 ✅ inner() still has access to message ✅ That memory power = Closure 🌟 Why Closures Are Useful? Private data (hidden variables) Remembering values (callbacks, timers) Custom functions (pre-filled data) Example: function greet(name) { return () => console.log("Hello " + name); } const hiJohn = greet("John"); hiJohn(); // Hello John 🔹One-line Definition: Closure = Function + Remembered outer variables If you found this helpful, follow for more: JavaScript | Full Stack | Real-world Coding Tips #JavaScript #Closures #Coding #WebDevelopment #LearnJS #Cognothink

To view or add a comment, sign in

Explore content categories