What is a closure in JavaScript?
A closure is a function that keeps access to the variables of the place where it was created, even after that outer function has finished.
function makeCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter());
console.log(counter());
console.log(counter());
Output:
Tutorials Class - Output Window
1
2
3
The variable count is private: only the inner function can change it. Closures are used for private data, counters, callbacks and function factories.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |