Why should you avoid polluting the global scope?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
Because the global scope is the one namespace every script on the page shares. Anything you put there can be read, overwritten, or accidentally shadowed by code you did not write and cannot change.
The concrete problems
- Name collisions. You define
window.config; an analytics snippet defineswindow.config. Last one to load wins, and the failure surfaces somewhere unrelated. - Order dependence. Globals turn your code into an implicit sequence — this file must load before that one — with nothing in the source saying so.
- Nothing is encapsulated. Any code can mutate
window.stateat any time, so a wrong value has no single place to have come from. That is the hardest class of bug to track down. - No garbage collection. A global reference lives for the life of the page, so a large object parked on
windowis a leak by definition. - Security. Extensions, embedded third-party scripts, and anything injected can read your globals. Tokens and user data do not belong there.
- Bad tooling. A global is invisible to the bundler: it cannot be tree-shaken, renamed, or type-checked, and you cannot grep for its importers because there are none.
How code leaks into global scope by accident
function f() { total = 5; } // no declaration -> creates window.total
Strict mode makes that a ReferenceError, which is one of the main reasons to use it. ES modules are strict automatically. A top-level var or function in a classic script also lands on window.
What to do instead
Use modules. A module has its own scope, so top-level bindings are private until exported, and every dependency is stated in an import.
// config.js
export const config = { apiUrl: '/api' };
Before modules the same effect came from an IIFE, which is why every older library is wrapped in one and exposes a single global.
When a global is acceptable
A deliberate, namespaced, documented one: window.dataLayer for analytics, a single window.__MY_APP__ for debugging hooks, or a feature-detection flag. One name, chosen on purpose, is nothing like twenty names that leaked.
