JavaScript - Global Variables

Overview

Estimated time: 10–20 minutes

Globals are accessible everywhere but can cause collisions. Prefer modules or local scope.

Learning Objectives

  • Identify the global object (globalThis).
  • Understand how var attaches to window in browsers.
  • Avoid accidental globals and name collisions.

Prerequisites

Global object

// Cross-platform reference
const root = globalThis; // window in browsers

Creating globals (avoid)

// Avoid: polluting the global namespace
window.appVersion = '1.0.0';

Safer patterns

// Use modules or closures to encapsulate
const config = (() => {
  const secret = 'token';
  return { version: '1.2.3' };
})();

Common Pitfalls

  • Implicit globals by assigning undeclared variables (throws in strict mode).