Challenge 05 — Closure over large scope

Find why small callbacks retain huge amounts of memory.

Mission

Small callbacks retain an entire large array via closure.

DevTools checklist

  1. Take snapshot (A)
  2. Click Start leaking — wait ~10 seconds
  3. Force GC → snapshot (B) → Comparison
  4. Inspect Closure entries — check retained size

Expected signals

  • Closure count increases
  • High retained size relative to shallow size
  • Array and Object held inside closure context

Hints & solution

Hint

Each callback only uses huge.length, but JavaScript closures capture the entire lexical scope — including the 40,000-element array.

Solution

Callbacks are stored in an array. Each one closes over a large huge array from its creation scope, retaining it even though only .length is read.

// Fix: extract only what you need before creating the callback
const len = huge.length;
const cb = () => len;

// Or clear the callbacks array when done
callbacks.length = 0;

← Lesson: Closure leaks · All challenges