Global variables
What global variables are
A global variable is a variable accessible everywhere in the code.
In the browser it is stored on the
windowobject, in Node.js onglobal.
var user = 'Tim'; // global variable
console.log(window.user); // "Tim"Global variables are visible to all functions, modules, and scripts, and they live until the program finishes or the page reloads.
Why this is dangerous
1. Naming conflicts (overwriting)
Different parts of a program (or third-party libraries) can accidentally use the same name.
var config = { darkMode: true };
// somewhere in a library
var config = { theme: 'light' };
console.log(config); // { theme: 'light' }You cannot "protect" a global variable - any part of the code can change it.
2. Hard to debug and test
When a variable is global, it is impossible to know:
- who changed it;
- when it changed;
- who depends on it.
This complicates the logic and makes bugs unpredictable.
let counter = 0;
function increase() {
counter++;
}
function reset() {
counter = 0;
}
increase();
reset(); // someone called it - and reset the whole state3. Broken encapsulation
Global variables break modularity. Every part of the program knows about every other part - there is no "isolated" code.
This contradicts the principles of OOP and pure functions (which do not depend on external state).
4. Memory leaks
If a global variable references a large object, it will never be removed by the garbage collector until the page reloads.
window.cache = new Array(1_000_000).fill('data');
// this array stays in memory the whole timeBecause the GC (Garbage Collector) cannot remove a variable that has a global reference.
5. Poor compatibility between modules and libraries
If you use several libraries, and each one defines its own global variables, "namespace collisions" occur.
// library A
window.$ = function(selector) { ... };
// library B
window.$ = 42;The browser simply overwrites the value of $,
and all your jQuery code stops working.
6. Harder to refactor and reuse
If code depends on global variables, you cannot just "cut and paste" it into another project - it will not work without all those same globals.
7. Problems with asynchronous code
Asynchronous code (timers, promises, async/await) can access the same global variable at different points in time, and the values can be unexpected.
let user = 'Tim';
setTimeout(() => console.log(user), 1000);
user = 'Alice';
// a second later: "Alice", not "Tim"Local variables inside a function protect against such effects.
How to avoid global variables
1. Use let / const inside functions or blocks
function run() {
const result = 42;
console.log(result);
}
run();
console.log(result); // ReferenceError2. Use modules (ES Modules, CommonJS)
Each module has its own scope and exports only what is explicitly specified.
// utils.js
export const sum = (a, b) => a + b;
// main.js
import { sum } from './utils.js';Now the variables inside utils.js do not "leak" into the global context.
3. Use objects or namespaces
If you need to store shared data, keep it in an object rather than a bare global variable.
const App = {
config: { darkMode: true },
state: {},
init() { console.log('App started'); }
};
App.init();Everything is grouped and does not conflict with other libraries.
4. Use closures
You can create a "private space" that is not accessible from outside.
const counter = (function() {
let value = 0;
return {
inc() { value++; },
get() { return value; }
};
})();
counter.inc();
console.log(counter.get()); // 1The value variable is protected and did not "leak" into the global scope.
5. Use "use strict"
In strict mode, JS does not allow implicitly creating global variables:
"use strict";
function test() {
x = 10; // ReferenceError
}Summary
| Problem | Why it is dangerous |
|---|---|
| Naming conflicts | Different scripts can redefine variables |
| Broken modularity | The code stops being independent |
| Memory leaks | Variables live until reload |
| Testing difficulty | The current state cannot be predicted |
| Implicit behavior | Hard to know who changes data and when |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.