Typorithm · medium

Closures for Private State

closure-private-stateinterview-questionsclosuresprivate-statefactory
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Closures for Private State

0%

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.

01

A closure keeps enclosing variables alive after the outer function returns.

02

A factory can return functions that share one private variable.

03

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 calls

Read the implementation

Connect each part of the code to the concept before you type.

1. Factory function

makeCounter is a factory: each call creates a fresh scope with its own private state.

function makeCounter() {

2. Private variable

count is local to makeCounter, so no code outside can read or assign it directly.

let count = 0                 // private — unreachable from outside

3. Closing over state

The returned arrow function closes over count, keeping it alive after makeCounter returns.

increment: () => ++count,   // closes over count

4. State persists

Because the closure keeps count alive, repeated calls accumulate state instead of resetting.

c.increment()                   // 1 — count lives on between calls

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Closures for Private State: Lesson & Practice · Typorithm | ApplyDjinn