Notes on closures, after the fourth try
Every time I think I get it, JavaScript hands me another shape. This is the version that finally stuck.
Every time I think I get it, JavaScript hands me another shape. This is the version that finally stuck.
Every time I think I understand closures, I run into a shape I haven’t seen before. But this time — after the fourth serious attempt at really getting it — something finally clicked.
A closure is a function that remembers the variables from the scope it was defined in. Not the scope it’s called in — the scope it was created in.
function outer() { const secret = "password";
return function inner() { console.log(secret); };}
const reveal = outer();reveal(); // 'password' — even though we're not inside outer() anymoreThe returned inner function “closes over” the variable secret. It keeps that reference alive.
Closures are the foundation for:
Once I stopped thinking of them as “functions that remember things” and started thinking of them as “scope that didn’t get thrown away,” everything made more sense.
The fourth time was the charm.