Closure
In computer programming, a closure is a technique for implementing lexically scoped name binding in a language with first-class functions.
In JavaScript, a function creates a closure context.
As shown by the following code, the inner function maintains access to the count variable even after createCounter() has finished executing.
js
function createCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
See also
- Closures in JavaScript
- Closure on Wikipedia