JavaScript Internals (521 Qs)•Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)
What are the problems with global variables
The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.
Practical Code Example
javascript
// Danger 1: Accidental overwrites and collisions across scripts
var currentUser = 'Alice'; // Script A
// In third-party script B:
var currentUser = { id: 99 }; // Overwrites Script A without warning!
// Danger 2: Memory leaks (globals stay in memory for page lifetime)
window.hugeArray = new Array(1000000).fill('data');