1. Factory function
makeCounter is a factory: each call creates a fresh scope with its own private state.
function makeCounter() {Typorithm · medium
Step 1 of 8 · intro card
Closures & Scope
A closure keeps its enclosing variables alive after the outer function returns, so a factory like makeCounter can return functions that share private state. The count variable is unreachable from outside, yet increment and get both close over it — the foundation of the module pattern.
When makeCounter returns, its local count would normally disappear — but the returned functions close over it, so JavaScript keeps that variable alive for as long as the closures exist.
Because increment and get both close over the same count, they share one private piece of state: incrementing through one is visible to the other, yet no outside code can touch count directly.
This is the module pattern: a factory exposes a small public API (increment, get) while hiding its internals behind the closure, giving you true private state without classes or # fields.
A closure keeps enclosing variables alive after the outer function returns.
A factory can return functions that share one private variable.
Exposing a small API while hiding state is the module pattern.
function makeCounter() {
let count = 0 // private — unreachable from outside
return {
increment: () => ++count, // closes over count
get: () => count,
}
}
const c = makeCounter()
c.increment() // 1 — count lives on between callsConnect each part of the code to the concept before you type.
makeCounter is a factory: each call creates a fresh scope with its own private state.
function makeCounter() {count is local to makeCounter, so no code outside can read or assign it directly.
let count = 0 // private — unreachable from outsideThe returned arrow function closes over count, keeping it alive after makeCounter returns.
increment: () => ++count, // closes over countBecause the closure keeps count alive, repeated calls accumulate state instead of resetting.
c.increment() // 1 — count lives on between callsRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.