What is a Closure in JavaScript?
A closure is a feature in JavaScript where an inner function remembers and can access variables from its outer function, even after the outer function has finished execution.
In simple words:
A closure allows a function to remember its lexical scope.
Why Closures Exist in JavaScript
JavaScript uses lexical scoping, which means:
- Inner functions can access variables of outer functions
- Functions are first-class citizens (they can be returned, stored, and passed)
Closures naturally happen because of this behavior.
Example
function outerFunction() { let message = "Hello from outer function";
function innerFunction() { console.log(message); }
return innerFunction;}
const myFunc = outerFunction();myFunc();Output
Hello from outer functionExplanation
- innerFunction() accesses message
- outerFunction() has already finished execution
- Still, message is remembered - Closure
How Closures Work
When a function is created:
- JavaScript stores its lexical environment
- Even after the outer function ends, the inner function keeps a reference to that environment
So the variables are not destroyed.
Closure with Parameters
function greet(name) { return function () { console.log("Hello " + name); };}
const greetNikhil = greet("Nikhil");greetNikhil();Output
Hello Nikhil- name is remembered
- greet() is already executed
- Closure is formed
Practical Use Cases of Closures
1. Data Privacy (Encapsulation)
function counter() { let count = 0;
return function () { count++; return count; };}
const increment = counter();increment(); // 1increment(); // 2count cannot be accessed directly
Data is protected
2. Function Factories
function multiplyBy(x) { return function (y) { return x * y; };}
const double = multiplyBy(2);double(5); // 103. Maintaining State
Closures help maintain values between function calls without using global variables.
Difference Between Closure and Noramal Function Call
| Feature | Normal Function | Closure |
|---|---|---|
| Remembers variables | No | Yes |
| Preserves state | No | Yes |
| Used for encapsulation | No | Yes |
Advantages of Closures
- Data hiding and security
- Better memory management
- Cleaner and modular code
- Essential for callbacks and async code
Disadvantages of Closures
- Higher memory usage if overused
- Can cause memory leaks if not handled properly
- Debugging can be tricky for beginners
When to Use Closures
- When you need private variables
- When maintaining state
- When creating reusable functions
- When working with callbacks and event handlers
Two Minute Drill
- A closure is created when a function remembers its outer variables
- Inner functions can access outer function variables evern after execution
- Closures are formed automatically, not manually
- Used for data privacy, state management and function factories
- let works better than var in closures
- Closures are powerful but should be used wisely
