Global Variables and Window Pollution
You'll learn how accidentally created global variables can slowly fill up memory and how to prevent them from polluting your page's lifespan.
What Are Accidental Global Variables?
When you forget let, const, or var in your JavaScript, the variable automatically attaches to the global window object and persists for the entire page session. Think of the global scope like a closet that never gets cleaned—every item you toss in stays there until you close the door (refresh the page).
How They Happen
The most common culprits:
// Forgot declaration keyword
function updateUser() {
userName = "Alice"; // Oops! Now window.userName exists forever
}
// Typo in assignment
let counter = 0;
function increment() {
conter = 1; // Typo creates window.conter
}
// This reference in callbacks
function Handler() {
this.data = [];
}
Handler.prototype.load = function() {
// Called without 'new', 'this' is window
this.data.push(item); // window.data grows forever
}
Why This Matters
Every accidental global variable takes up memory and is never garbage collected. In long-running single-page applications, hundreds of these mistakes can accumulate, slowly consuming memory and degrading performance.
Prevention Strategies
- Use strict mode: Add
"use strict";at the top of files—it throws errors for undeclared variables - Use
constandlet: Modern block-scoped declarations prevent accidental globals - Linting tools: ESLint catches these mistakes during development
- Modular scope: Keep code in modules or IIFEs to limit scope exposure
Key Takeaway: Forgetting variable declarations creates permanent global variables that survive your page's entire lifetime—always use const, let, or strict mode to catch these memory-wasting mistakes early.