What is a closure in JavaScript?
Asked by ahillg199327 days ago
34 views
Explain closures with examples.
0
1 answers
1 Answer
A **closure** in JavaScript is a feature where an inner function has access to variables from its outer (enclosing) function’s scope, even after the outer function has finished executing. This means the inner function "remembers" the environment in which it was created.
### How Closures Work
When a function is defined inside another function, the inner function forms a closure. It can access:
- Its own local variables
- Variables in the outer function’s scope
- Variables in the global scope
Even if the outer function returns and finishes execution, the inner function retains access to those outer variables.
### Example of a Closure
```javascript
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const counter = outer(); // `outer` runs and returns `inner`
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
```
Here, `inner` is a closure. It remembers the variable `count` from the `outer` function’s scope. Each time `counter()` is called, it increments and logs `count`, even though `outer()` has already finished running.
### Why Closures Are Useful
- **Data privacy:** Closures allow you to create private variables that cannot be accessed directly from outside.
- **Function factories:** You can create functions with preset configurations.
- **Callbacks and asynchronous code:** Closures help maintain state in event handlers, timers, and promises.
### Another Example: Private Variables
```javascript
function makeCounter() {
let count = 0;
return {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
}
};
}
const counter = makeCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1
```
Here, `count` is private to the returned object’s methods, demonstrating encapsulation via closure.
---
In summary, closures enable powerful patterns in JavaScript by preserving the scope of variables in nested functions, even after the outer function has completed. They are fundamental to understanding JavaScript’s function scope and are widely used in many programming scenarios.
0
0
by Olivia Brown15 days ago
