Sub topic 2
The Global Scope
This chapter assumes you know basic JavaScript syntax, can declare variables with var, let, and const, can write and call functions, and can run code in a browser console or Node.js. The previous chapter defined lexical scope: a name's visibility depends on where it is written in the source. Here we look at the outermost scope, the one every other scope eventually leads back to.
What the Global Scope Is
The global scope is the outermost scope of a JavaScript program. Code written at the top level of a classic script, outside every function and block, runs in it. A name declared there can be read from anywhere in the program unless an inner scope declares the same name.
When the engine resolves a name, it searches the global scope last. If the name is not found there either, reading it throws a ReferenceError. A later chapter covers this search, the scope chain, step by step. For now, remember that the global scope is the end of every lookup.
The global scope is less simple than it looks. It has two separate storage areas, and the kind of declaration you use decides which area a name goes into.
The Global Object
Every JavaScript environment provides a global object. Its properties can be used as bare names anywhere in the program. Built-ins such as Math, JSON, setTimeout, and console are reached through it.
The global object has a different name in each environment:
| Environment | Traditional name | Standard name |
|---|---|---|
| Browser main thread | `window` (also `self`) | `globalThis` |
| Web Worker | `self` | `globalThis` |
| Node.js | `global` | `globalThis` |
globalThis was added in ES2020 and works in all of these environments. Use it when code has to run in more than one of them.
Any property on the global object can be read as a plain variable:
globalThis.answer = 42;
console.log(answer); // 42
console.log(typeof globalThis.Math); // "object"Two Storage Areas: Object Record and Declarative Record
The specification calls the global scope's storage the global environment record. It has two parts:
- The object record is backed by the global object itself. Top-level
vardeclarations and top-level function declarations create properties here. - The declarative record is separate storage that is not visible as properties of any object. Top-level
let,const, andclassdeclarations live here.
Both parts belong to the same global scope, so a name in either one can be used from anywhere. The only difference is whether the name also shows up as a property of globalThis.
Run this in a browser console or the Node.js REPL. Both evaluate input as a classic script, not as a module:
var appName = "demo";
function helper() { return "help"; }
let version = 2;
const debug = false;
console.log(globalThis.appName); // "demo"
console.log(typeof globalThis.helper); // "function"
console.log(globalThis.version); // undefined
console.log(globalThis.debug); // undefined
console.log(version); // 2 (still a global name)
console.log(debug); // falseversion and debug are global variables, but they are not properties of the global object. People often mix up these two ideas. "Global" describes where a name is visible. "Property of globalThis" describes where it is stored.
Lexical Bindings Win Over Properties
The declarative record is checked first, so a top-level let can hide a global object property that has the same name:
globalThis.mode = "property";
let mode = "lexical";
console.log(mode); // "lexical"
console.log(globalThis.mode); // "property"Two values now exist under one name. Code that reads mode sees one of them, and code that reads globalThis.mode sees the other. Avoid this pattern. It is shown here because it shows how the two records relate.
var Globals Are Non-Configurable
A top-level var creates a property that cannot be deleted. A property created by plain assignment to globalThis can be deleted:
var fixed = 1;
globalThis.loose = 2;
console.log(Object.getOwnPropertyDescriptor(globalThis, "fixed").configurable); // false
console.log(Object.getOwnPropertyDescriptor(globalThis, "loose").configurable); // true
console.log(delete globalThis.fixed); // false (sloppy mode; strict mode throws TypeError)
console.log(delete globalThis.loose); // true
console.log(typeof loose); // "undefined"Assigning to a name that was never declared also creates a deletable property. The chapter on accidental globals covers that case and how strict mode prevents it.
One Global Scope, Many Scripts
In a browser, every classic <script> element on a page shares the same global scope. A global declared in one script can be read in another script that runs later. This is how libraries loaded with script tags have always exposed themselves, for example jQuery's $.
You can see the same behavior in Node.js with the built-in vm module. vm.runInThisContext runs a string as a separate classic script in the current global scope, the same way a second script tag would. Save this as scripts.js and run node scripts.js:
const vm = require("node:vm");
// "Script A" declares globals.
vm.runInThisContext('var shared = "from script A";');
vm.runInThisContext("let counter = 1;");
// "Script B" sees both.
vm.runInThisContext("console.log(shared);"); // "from script A"
vm.runInThisContext("counter += 1; console.log(counter);"); // 2
vm.runInThisContext("console.log(globalThis.counter);"); // undefined
// "Script C" tries to redeclare a name with let.
try {
vm.runInThisContext('let shared = "from script C";');
} catch (e) {
console.log(e.name); // "SyntaxError"
}The last script throws a SyntaxError before any of its code runs. When a script starts, the engine first checks its top-level let, const, and class names against names that already exist in the global scope. A collision with an existing var or lexical name causes the whole script to fail. Two var declarations of the same name do not collide. The second one silently reuses the first.
Built-in Globals and Collisions
The global object already holds many properties. A top-level var with the same name as one of them does not create a new variable. It reuses the existing property, and that property may have unusual behavior.
The best-known case is name in browsers. window.name is an accessor that converts any value you assign into a string:
// Browser console only
var name = 42;
console.log(typeof name); // "string"
console.log(name); // "42"let name = 42 would create a binding in the declarative record, which shadows the property, and typeof name would be "number". Some global properties cannot be shadowed even this way. undefined, NaN, and Infinity are non-writable and non-configurable, so var undefined = 1 at the top level has no effect, and let undefined = 1 at the top level throws a SyntaxError.
Where Top-Level Code Is Not Global
Not every file's top level is the global scope:
| How the code runs | Is top-level `var` a `globalThis` property? | Is the top level the global scope? |
|---|---|---|
| Browser classic `<script>` | Yes | Yes |
| Browser console, Node REPL, `node -e` | Yes | Yes |
| Node.js CommonJS file (`node file.js`) | No | No, it is wrapped in a function |
| ES module (`type="module"`, `.mjs`) | No | No, it has module scope |
Node.js wraps every CommonJS file in a function before running it. That wrapper is where require, module, exports, __filename, and __dirname come from. So a top-level var in a Node file is function-scoped to the wrapper:
// Save as wrapped.js and run: node wrapped.js
var notGlobal = 1;
console.log(globalThis.notGlobal); // undefined
console.log(typeof module); // "object"
console.log(typeof require); // "function"The scope that is actually global in Node is still there. You can reach it only through globalThis or by assigning to an undeclared name. ES modules have their own module scope, which a later chapter covers.
Common Errors
- Expecting
globalThis.xto show a top-levellet x. It will beundefined, because lexical globals are not properties. - Expecting a top-level
varin a Node.js file to be global. CommonJS files are wrapped in a function, so it is not. - Using
var name,var status, orvar topin browser scripts. These names already exist onwindowand may behave strangely. - Loading two scripts that both declare the same name with
letorconst. The second script throws aSyntaxErrorand none of it runs. - Using
deleteon avarglobal. It returnsfalsein sloppy mode and throws in strict mode.
Exercise
In a browser console (classic script), you run var a = 1; let b = 2; function c() {}. What do "a" in globalThis, "b" in globalThis, and "c" in globalThis each return, and why?
Show answer
They return true, false, and true. Top-level var declarations and function declarations create properties on the global object (the object record). Top-level let goes into the declarative record, which is still global scope but not a property of globalThis.
Exercise
A page loads script one, which contains var config = {}, and then script two, which contains const config = { debug: true }; console.log("loaded");. What happens when script two runs?
Show answer
Script two throws a SyntaxError ("Identifier 'config' has already been declared") before it executes anything, so "loaded" is never printed. Both scripts share one global scope, and a lexical declaration cannot reuse a name that a var already declared there.
Exercise
You save var total = 10; console.log(globalThis.total); in a file and run it with node file.js. It prints undefined. Explain, and give a one-line change that makes the value reachable as globalThis.total.
Show answer
Node.js wraps CommonJS files in a function, so var total is local to that wrapper function and is not global. Writing globalThis.total = 10; creates the property on the global object explicitly.