Closures
Understand Closures
A closure is a function that keeps access to variables from the lexical scope where it was created, even after the enclosing function has returned.
What you will learn: the purpose of closures, the rules TypeScript checks, and what its JavaScript behavior looks like in a runnable example.
What you’ll learn
- Explain how closures works and where its type rules apply.
- Predict the exact output of the closures example.
- Diagnose a common issue: Do not assume closure-captured variables reset every time the returned function runs.
Build the mental model
The captured state persists because the returned function still uses it. Each call to makeCounter creates its own independent count. Closures are useful for encapsulation, but long-lived closures can also retain data longer than intended.
Key distinction: TypeScript checks the declared types during development; emitted JavaScript carries out the value-level operation at runtime. A type declaration alone never validates untrusted runtime input.
See the relationship
Read this illustration from the first labeled part to the last. Compare it with the example and identify which parts are type checks and which parts run in JavaScript.
Run the complete TypeScript example
This self-contained example uses fixed values, so it runs without reading input or depending on an external service. Paste it into the TypeScript Playground or save it as main.ts.
TypeScript program
function makeCounter(): () => number {
let count = 0;
return () => ++count;
}
const first = makeCounter();
const second = makeCounter();
console.log(first());
console.log(first());
console.log(second());Verified output
1
2
1Run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. For projects with a tsconfig.json, build using that configuration instead.
Trace every important step
first captures one count initialized to zero; its calls return 1 then 2. second captures a different count, so its first call returns 1 rather than 3.
Check each step: identify the input values, follow the JavaScript operation in execution order, and match the final expression with the exact output shown. An annotation can reject invalid source before execution, but does not change the value printed.
Avoid these common mistakes
Do not assume closure-captured variables reset every time the returned function runs. The enclosing function reruns only when you call it again.
How to debug: reproduce the issue in a minimal example. For compiler errors, inspect the inferred and declared types; for a runtime surprise, log the actual values and follow their references or branches.
Practice and experiment
Add a reset operation using an object with increment and reset functions that share one closed-over count.
Practice routine: predict the result on paper, edit one part of the code, compile under --strict, run the JavaScript, and explain whether TypeScript caught an error or JavaScript simply behaved differently.
Check your understanding
Review the key idea
Closures: A closure is a function that keeps access to variables from the lexical scope where it was created, even after the enclosing function has returned.
first captures one count initialized to zero; its calls return 1 then 2. second captures a different count, so its first call returns 1 rather than 3.
Before continuing, explain one valid use case, one common pitfall, and the separation between compile-time checking and runtime behavior for this feature.
Reaching the recap and completing the quizzes are separate milestones.