Closures
A closure is a function that keeps access to the variables of the scope where it was defined, even after that scope has finished running.
Basic example
Section titled “Basic example”function createCounter() { let count = 0;
return function increment() { count += 1; return count; };}
const counter = createCounter();counter(); // 1counter(); // 2Common pitfall: var in loops
Section titled “Common pitfall: var in loops”for (var i = 0; i < 3; i++) {for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0);}With var it prints 3 3 3. With let each iteration gets its own binding, so it prints 0 1 2.
Same idea in other languages
Section titled “Same idea in other languages”function createCounter(): () => number { let count = 0; return () => ++count;}def create_counter(): count = 0
def increment(): nonlocal count count += 1 return count
return incrementTerminal
Section titled “Terminal”node counter.js