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).

js
CopyEdit
function outer() {
let name = "Mohit";
function inner() {
console.log(name); // Can access 'name' from outer scope
}

inner();
}
outer(); // "Mohit"

✅ 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

js
CopyEdit
function greet(name) {
return function(message) {
console.log(`${message}, ${name}`);
};
}

let greetMohit = greet("Mohit"); // `greet` returns a function
greetMohit("Hello"); // "Hello, Mohit"

✅ 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:

js
CopyEdit
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}

let increment = counter();
console.log(increment()); // 1
console.log(increment()); // 2

count is private inside the function.

🔹 Function Factories:

js
CopyEdit
function multiplyBy(x) {
return function(y) {
return x * y;
};
}

let double = multiplyBy(2);
console.log(double(5)); // 10

🔹 Event Listeners & Async Operations:

Closures help you preserve values in setTimeout, API calls, etc.

js
CopyEdit
for (var i = 1; i <= 3; i++) {
setTimeout(function() {
console.log(i); // prints 4 three times
}, 1000);
}

🔁 Fix with closure (IIFE or let):

js
CopyEdit
for (let i = 1; i <= 3; i++) {
setTimeout(function() {
console.log(i); // prints 1, 2, 3
}, 1000);
}

✅ 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.