Skip to content

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.

counter.js
function createCounter() {
let count = 0;
return function increment() {
count += 1;
return count;
};
}
const counter = createCounter();
counter(); // 1
counter(); // 2
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.

function createCounter(): () => number {
let count = 0;
return () => ++count;
}
Run it
node counter.js