Course contentsShow
← JavaScript
Lesson 1871 of 2,72339. Memory Management and GCFree lesson

Accidental Global Variables

How undeclared variables or incorrect 'this' bindings create persistent global references that never get collected.

Accidental Global Variables

You'll learn: How forgetting let, const, or var turns variables into globals that the garbage collector can never reclaim, slowly leaking memory.

The Core Problem

In JavaScript, if you assign to a variable without declaring it with let, const, or var, the engine automatically creates a global variable. This isn't just bad practice—it's a memory leak waiting to happen. Global variables are considered GC roots (as you learned earlier), so they and everything they reference will never be collected, even if you never use them again.

Similarly, incorrect this bindings in functions can accidentally attach properties to the global object (window in browsers, global in Node.js), creating persistent references.

How It Happens

function processUser(data) {
  userId = data.id;  // Oops! Missing 'let' or 'const'
  // ... process the user
}

processUser({ id: 12345, name: "Alice", avatar: largeImageData });
// userId is now global and will NEVER be garbage collected

Even after processUser finishes, userId lives forever in global scope. If it references large objects, those leak too.

The 'this' Trap

function Timer() {
  this.count = 0;
  setTimeout(function() {
    this.count++;  // 'this' is window/global, not the Timer instance!
  }, 1000);
}

Here, this.count accidentally creates window.count, another global leak.

Key Takeaway: Always declare variables with let, const, or var, and be vigilant about this context—accidental globals are GC roots that create permanent memory leaks because the garbage collector considers them always reachable.