A closure captures the surrounding scope
When a function is defined inside another function, it remembers the variables in that outer scope even after the outer function has returned. The inner function plus its captured scope is the closure.
function makeCounter() {
let count = 0 // lives in makeCounter's scope
return function increment() {
count++ // still accessible closure over count
return count
}
}
const counter = makeCounter()
console.log(counter()) // 1
console.log(counter()) // 2
console.log(counter()) // 3