JavaScript Tutorial in Hindi #22 | Closure & Lexical Scope (2025)
✅ 1. What is Lexical Scope in JavaScript?
Lexical scope means a function can access variables from its outer scope (where it was defined, not where it's called).
✅ 2. What is a Closure?
A closure is a function that remembers and has access to variables from its outer function, even after that outer function has finished executing.
✅ 3. Simple Example of Closure
✅ Here, greetMohit
remembers the variable name
even after greet
has executed — that’s a closure.
✅ 4. Why and Where Closures Are Useful
Closures are powerful for:
🔹 Data Privacy / Encapsulation:
✅ count
is private inside the function.
🔹 Function Factories:
🔹 Event Listeners & Async Operations:
Closures help you preserve values in setTimeout
, API calls, etc.
🔁 Fix with closure (IIFE or let
):
✅ 5. Common Interview Questions on Closures
🔸 Q1: What is a closure?
✅ A function with access to its outer scope, even after the outer function has returned.
🔸 Q2: Why are closures important?
✅ For data privacy, maintaining state, and handling async code.
🔸 Q3: How can closures help simulate private variables?
✅ By returning a function that accesses a variable in the outer function but doesn’t expose it directly.
🔸 Q4: What is the difference between lexical scope and closure?
✅ Lexical scope is where variables are accessible based on code structure;
Closure is the behavior of retaining access to outer scope variables after the outer function has executed.