Closures and Lexical Scope
A closure
is a function that retains access to its outer scope, even after the outer function has finished executing.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
This works because of lexical scoping
— functions remember the environment in which they were created.