Chapter IX · Scope

Global Scope

Global scope is the outermost scope of a program — anything declared here, outside every function and block, is visible from anywhere else in the code.

01 How It Works

Think of a notice board in the lobby of a building — everyone who works anywhere in the building walks past it and can read what's pinned there.

In a browser, top-level var declarations and function declarations actually become properties of the global object (window). Top-level let, const, and class do not — they live in a separate global lexical environment that's still visible everywhere, but doesn't pollute window. Every function you write, no matter how deeply nested, can see global-scope variables, because every scope's chain eventually reaches the global scope at its root.

example.js
const appName = "MyApp";

function logApp() {
  console.log(appName); // accessible — logApp() can see the global scope
}
logApp(); // "MyApp"
  1. 1. A variable, function, or class is declared outside of any function or block.

  2. 2. It becomes part of the global scope, the outermost link in every scope chain.

  3. 3. Any code anywhere in the program can read (and, if not const, reassign) it.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
const API_URL = "https://api.example.com";

function fetchURL() {
  return API_URL; // reads the global constant
}

// Common mistake: relying on too many globals makes code hard to
// reason about, since ANY function anywhere could be reading or
// changing them. Prefer passing values as parameters where you can.

Key Takeaway

Global scope is convenient because everything can reach it, which is exactly why overusing it makes large programs fragile — minimize what you put there.

Related Concepts