0
JavaScript · Advanced JavaScript
New technique
Scope and closures
A function remembers where it was written, and every variable around it. That memory is called a closure.
An inner function can use the variables of the function around it: that's lexical scope: what you can see depends on where the code is written.
A closure is a function that keeps access to those outer variables, even after the outer function has returned.
function makeCounter() {
let count = 0;
return () => {
count++;
return count;
};
}
const next = makeCounter();
next(); // 1
next(); // 2: count lives on inside the closure- Each call to
makeCounter()creates a freshcount, private to the function it returns. - Closures are everywhere: every event handler or callback that uses a variable from around it is one.