Closures

Use lexical scope to retain private state and build reusable functions.

Lesson content

🎯 Goal By the end of this lesson, you'll understand: What is a Closure? Why do we need Closures? How do Closures work? Real-world examples Interview questions What is a Closure? A Closure is a function that remembers the variables from its outer function, even after the outer function has finished executing. Simple Definition: A closure allows an inner function to access the outer function's variables even after the outer function has returned. Real-Life Example 🔒 Imagine you have a locker . You put your books inside. You lock it. Later, you open it with your key. Even though you left the room, your books are still inside the locker. Similarly: 📦 Outer Function = Locker 🔑 Inner Function = Key 📚 Variables = Stored Data The inner function can still access those variables later. Example 1: Basic Closure function outer () { let message = "Hello" ; function inner () { console . log( message ); } return inner ; } const greet = outer (); greet (); Output Hello How It Works Step 1 outer (); message = "Hello" Step 2 return inner ; The inner function is returned. Step 3 greet (); Even though outer() has already finished, inner() still remembers: message = "Hello" This is called a Closure . Example 2: Counter function counter () { let count = 0 ; return function () { count ++ ; console . log( count ); }; } const increment = counter (); increment (); increment (); increment (); Output 1 2 3 Why? Normally, local variables disappear after the function ends. But because the inner function is using count , JavaScript keeps it alive. Example 3: Multiple Counters function counter () { let count = 0 ; return function () { count ++ ; console . log( count ); }; } const counter1 = counter (); const counter2 = counter (); counter1 (); counter1 (); counter2 (); counter1 (); Output 1 2 1 3 Each closure has its own private copy of count . Real-Life Example 💰 Imagine an ATM. function bankAccount ( balance ) { return function ( amount ) { balance -= amount ; console . log( "Remaining:" , balance ); }; } const withdraw = bankAccount ( 1000 ); withdraw ( 100 ); withdraw ( 200 ); Output Remaining: 900 Remaining: 700 The balance variable stays private inside the closure. Why Use Closures? Closures are useful for: ✅ Private variables ✅ Counters ✅ Data hiding ✅ Event handlers ✅ Callbacks ✅ Memoization (caching) Interview Example What is the output? function outer () { let name = "Ajay" ; return function () { console . log( name ); }; } const fn = outer (); fn (); Output Ajay Common Mistake function test () { let x = 10 ; } console . log( x ); Output ReferenceError: x is not defined x is local to test() . But if an inner function uses x , a closure keeps it alive. Where Are Closures Used? Event Listeners button . addEventListener( "click" , function () { console . log( "Button clicked" ); }); Timers setTimeout ( function () { console . log( "Executed after 2 seconds" ); }, 2000 ); Callbacks function process ( callback ) { callback (); } Function vs Closure Function Closure A reusable block of code A function that remembers variables from its outer scope Executes when called Executes with access to remembered variables Doesn't automatically preserve local variables Preserves outer variables even after the outer function finishes Visualization outer() │ ├── message = "Hello" │ └── returns inner() │ ▼ Closure Created │ ▼ inner() still remembers message = "Hello" Key Points ✅ A Closure is created when an inner function accesses variables from its outer function. ✅ The inner function remembers those variables even after the outer function has finished. ✅ Closures are commonly used for private data , counters , callbacks , and event handlers . ✅ Each closure has its own independent state . Easy Formula Outer Function → Inner Function → Remembers Variables = Closure 🔒