Q1. What is a Closure in JavaScript?
A closure is a function that remembers and can access variables from its outer (parent) function even after the outer function has finished executing.
Normally, when a function finishes execution, its variables should disappear. But in closures, the inner function remembers those variables and can still use them later.
Normally, when a function finishes execution, its variables should disappear. But in closures, the inner function remembers those variables and can still use them later.
Q2. Why are Closures used in JavaScript?
Closures are mainly used for:
- Data privacy
- Maintaining state
- Creating function factories
- Callback functions
- Module pattern
Q3. How do Closures provide Data Privacy?
Closures allow variables to be accessed only inside a specific function, preventing outside access.
Example
Output
Example
function createCounter() { let count = 0;
return function() { count++; return count; };}
const counter = createCounter();
console.log(counter());console.log(counter());console.log(counter());Output
1
2
3Q4. When is a Closure created?
A closure is created whenever a function is defined inside another function.
Whenever an inner function accesses variables from its parent function, JavaScript automatically creates a closure.
Whenever an inner function accesses variables from its parent function, JavaScript automatically creates a closure.
Q5. What is the advantage of Closures?
Closures provide:
- Data encapsulation
- State preservation
- Cleaner code structure
- Avoid global variables
- Helps in functional programming
