What is global scope?

Global scope is the outermost scope: anything declared there can be read from anywhere in the program, which makes it convenient but risky.

How things become global

  • Top-level declarations in a classic script (<script> without type="module").
  • var and function declarations at the top level of a classic script also become properties of the global object (window in browsers). let/const are global but do not become window properties.
  • Assigning to an undeclared variable (count = 1) in sloppy mode silently creates a global. Strict mode throws instead.
  • Explicitly: globalThis.config = {...}.

Modules change the picture

In ES modules (and Node's CommonJS files) each file has its own module scope. Top-level variables are private to the module unless exported. This is why modern code rarely creates globals by accident.

globalThis

A standard way to reach the global object in any environment: window in browsers, self in workers, global in Node.

Why to avoid globals

  • Name collisions with other scripts, libraries or browser features.
  • Hidden dependencies: any code can change the value, which makes bugs hard to trace.
  • Testing: globals leak state between tests.

Prefer modules, pass values as arguments, and keep truly shared state in one well-defined place.

Code example

js
1"use strict";
2
3// globalThis works everywhere (browser, worker, Node)
4globalThis.appVersion = "2.1.0";
5console.log(appVersion); // readable from anywhere: "2.1.0"
6
7function readVersion() {
8 return appVersion; // found by walking up the scope chain
9}
10console.log(readVersion());
11
12// Strict mode stops accidental globals
13try {
14 undeclaredCounter = 1; // ReferenceError in strict mode
15} catch (e) {
16 console.log(e.name); // ReferenceError
17}
18
19// Shadowing a global inside a function
20function useLocal() {
21 const appVersion = "local";
22 return appVersion;
23}
24console.log(useLocal(), globalThis.appVersion); // local 2.1.0
25
26delete globalThis.appVersion; // clean up

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app