Write a function named makeCounter that returns another function. The returned function should increment and return a private count variable each time it is called.
A closure is a function that remembers the environment in which it was created. This means it has access to variables from its outer (enclosing) scope, even after the outer function has finished executing.
function outer() {
let count = 0;
function inner() {
count++;
return count;
}
return inner;
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Here, inner
forms a closure that retains access to count
defined in outer
.
JavaScript uses lexical scoping — the scope is determined by where functions and blocks are defined, not where they are called.