Global Namespace Pollution
You'll learn why carelessly adding properties to the global object creates conflicts and how modules solve this problem.
The Problem with Shared Space
Imagine a shared whiteboard in an office where everyone writes notes without labels or organization. Eventually, someone's grocery list overwrites another person's meeting notes. Global namespace pollution happens when multiple scripts add variables or functions to the global object (window in browsers), creating a chaotic, conflict-prone environment.
How Pollution Happens
Every time you create a variable with var in the global scope or assign directly to window, you're adding to the shared global namespace:
// script1.js
var config = { theme: 'dark' };
// script2.js (loaded later)
var config = { apiKey: '12345' }; // Overwrites the first config!
Both scripts think they're safe, but the second one silently destroys the first's data. If you're using third-party libraries, you have no control over what names they might claim.
Why This Matters
Global pollution causes:
- Silent bugs: Variables get overwritten without warnings
- Naming conflicts: Common names like
data,config, orutilscollide - Maintenance nightmares: Tracking down which script owns which global is painful
- Scalability issues: Adding new code becomes risky
The Module Solution
ES modules solve this by giving each module its own scope. Variables stay private unless explicitly exported, preventing accidental pollution. Modern let and const also help—they don't create window properties even in global scope.
Key Takeaway: Adding properties to the global object creates hidden conflicts and fragile code; modules provide isolated scopes that prevent these collisions and make code maintainable.