Typorithm · medium

Closures

closure-basicsjavascript-coreclosuresscopestate
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Closures

0%

Closures & Scope

A closure is an inner function bundled with the outer variables it references. count survives after makeCounter returns, giving each counter private, persistent state that only its returned function can touch.

When a function is created, it captures references to the variables in scope around it. That bundle of function plus captured environment is a closure.

makeCounter declares count and returns an arrow function that reads and increments it. Even after makeCounter has returned, the returned function still reaches the same count binding.

Because count is not exposed any other way, it acts as private state: each call to makeCounter produces an independent counter with its own count.

01

A closure pairs a function with the variables it captured.

02

Captured variables persist after the outer function returns.

03

Closures give functions private, encapsulated state.

function makeCounter() {
  let count = 0;
  return () => count += 1;
}
const next = makeCounter();

Read the implementation

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

1. Captured variable

count lives in makeCounter's scope; the returned function keeps a reference to it after makeCounter returns.

let count = 0;

2. Inner function

The arrow function closes over count, reading and updating the same binding on every call.

return () => count += 1;

3. Enclosing scope

Each call to makeCounter creates a fresh count, so each returned counter has its own private state.

function makeCounter() {

4. Live closure

next holds the inner function; calling next() repeatedly increments the captured count across calls.

const next = makeCounter();

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: Lesson & Practice · Typorithm | ApplyDjinn