Skip to main content

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 window object, in Node.js on global.

javascript
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.

javascript
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.

javascript
let counter = 0; function increase() { counter++; } function reset() { counter = 0; } increase(); reset(); // someone called it - and reset the whole state

3. 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.

javascript
window.cache = new Array(1_000_000).fill('data'); // this array stays in memory the whole time

Because 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.

javascript
// 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.

javascript
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

javascript
function run() { const result = 42; console.log(result); } run(); console.log(result); // ReferenceError

2. Use modules (ES Modules, CommonJS)

Each module has its own scope and exports only what is explicitly specified.

javascript
// 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.

javascript
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.

javascript
const counter = (function() { let value = 0; return { inc() { value++; }, get() { return value; } }; })(); counter.inc(); console.log(counter.get()); // 1

The 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:

javascript
"use strict"; function test() { x = 10; // ReferenceError }

Summary

ProblemWhy it is dangerous
Naming conflictsDifferent scripts can redefine variables
Broken modularityThe code stops being independent
Memory leaksVariables live until reload
Testing difficultyThe current state cannot be predicted
Implicit behaviorHard to know who changes data and when

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.