freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #6 of 61

closures · the function memory trick

LambdaVSThe Mutator
Lambda saysA closure is a function that remembers variables from where it was created.

When a function is defined inside another, it keeps access to the outer function's variables even after the outer one returns. That captured state is a closure — the basis of private data, factory functions, and memoization. It's why a counter factory can keep its own private count.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleWrite a makeCounter() factory whose returned function increments a private count.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>function makeCounter(){ let n=0; return ()=>++n; }
const c=makeCounter();
document.getElementById('o').textContent=[c(),c(),c()].join(' ');</script></body></html>
▶ Open the interactive comic issue
‹ Scope · Global · Function · BlockIife · Self-Invoking Patterns ›