Functions with a backpack
In the foundations course you learned that a function can see variables around it. Here's the twist: it keeps seeing them even after the outer function has finished. That's a closure, and it powers counters, private data, event handlers and much of modern JavaScript.
A function that returns a function
function makeCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const next = makeCounter();
console.log(next());
console.log(next());
const other = makeCounter();
console.log(other());A backpack: When a function is created, it packs a backpack with the variables around it. Wherever it travels, it carries the backpack — and can read and change what's inside.