Skip to content

Global variables

In browsers, the global object (window) is a GC root. Anything attached to it lives until you delete it or close the tab.

  • Assigning without declaration: leaked = [] (sloppy mode / implicit global)
  • window.myCache = data for debugging and forgetting
  • Libraries that attach to window
flowchart TD
  window[window GC root]
  leakStore[leakStore array]
  chunk1[Chunk objects]
  chunk2[More chunks]
  window --> leakStore
  leakStore --> chunk1
  leakStore --> chunk2
function ingest(rows) {
// Oops — no var/let/const in non-strict sloppy scripts
buffer = buffer || [];
buffer.push(...rows);
}

In modules (type="module") this throws ReferenceError — modules are strict. Leaks still happen via explicit window.x = ....

const buffer = [];
const MAX = 500;
function ingest(rows) {
buffer.push(...rows);
while (buffer.length > MAX) buffer.shift();
}

Or scope data to where it’s needed and let it go out of scope.

Live demo: accidental globals

Idle — click Start to push objects onto an accidental global array.

— MBPeak: — MB