Understanding Closures in JavaScript

JavaScript Learning – Today's Topic : Understanding Closures Have you ever seen a function “remember” variables even after its parent function has finished running? 🤔 That’s not magic — it’s called a Closure ✨ 🔍 What is a Closure? A closure is formed when an inner function “remembers” the variables of its outer function, even after that outer function has completed execution. In short: Functions remember the environment they were created in. Example 1: Simple Closure Javascript function outer() { let name = "Venkatesh"; function inner() { console.log("Hello, " + name); } return inner; } const greet = outer(); greet(); // Output: Hello, Venkatesh Explanation: • The outer() function returns inner(). • Even though outer() is done executing, the inner function still remembers the name — that’s closure! Example 2: Private Variables (Real-life Use) Javascript function counter() { let count = 0; return { increment: function() { count++; console.log(count); }, decrement: function() { count--; console.log(count); } }; } const myCounter = counter(); myCounter.increment(); // 1 myCounter.increment(); // 2 myCounter.decrement(); // 1 ✅ Here, count is private — you can’t access it directly from outside! Closures help in data hiding and encapsulation (like private variables in OOP). 🧠 Why Closures Are Useful ✅ Maintain state between function calls ✅ Implement data privacy ✅ Used in callbacks and event listeners ✅ Help create factory functions and module patterns In Simple Words A closure is like a backpack 🎒 — when a function travels, it carries the variables it needs from its home environment. #JavaScript #Closures #WebDevelopment #Coding #FrontendDevelopment #LearnToCode #JSConcepts #WebDev #Programming #Developer #CodeNewbie #100DaysOfCode #SoftwareEngineering #JavaScriptTips #CodeWithVenkatesh #WebTech #AsyncJS #TechLearning #InterviewPrep

To view or add a comment, sign in

Explore content categories