Sub topic 10
Top-Level Variables and globalThis
This chapter assumes you know the difference between function scope and block scope, and how hoisting works for var, let, and const, as covered in earlier chapters. Here we look at what happens when you declare variables outside of every function and block, at the very top of a file. The answer depends on two things: which keyword you use, and what kind of file the code runs in.
The global object and globalThis
Every JavaScript environment has a global object. It holds the built-ins (Math, JSON, setTimeout, console) and anything the host adds, such as document in a browser or process in Node.js.
For years, each environment gave this object a different name. You had to know where your code would run in order to reach it.
| Environment | Traditional name | Works with `globalThis`? |
|---|---|---|
| Browser main thread | `window` (also `self`, `frames`) | Yes |
| Web Worker | `self` | Yes |
| Node.js | `global` | Yes (Node 12+) |
| Deno, Bun | `globalThis` (`window` in older Deno) | Yes |
ES2020 added globalThis as one standard name that works everywhere. Use it whenever you mean "the global object" and you don't want to tie the code to one host.
console.log(typeof globalThis); // 'object'
console.log(globalThis.Math === Math); // true
console.log(typeof globalThis.setTimeout); // 'function'Two places a global can live
A common mental model says "a global variable is a property of the global object." That model is only half right. In a classic script, the global scope is made of two separate storage areas:
- An object record, backed by the global object itself. Top-level
vardeclarations and top-level function declarations go here, next to the built-ins. - A declarative record, a hidden storage area that is not attached to any object. Top-level
let,const, andclassdeclarations go here.
Both areas belong to the same global scope, so code can read either kind of variable by its plain name. Only the first kind shows up as a property on globalThis.
Seeing the difference in a classic script
The spine example shows the core fact:
// Run as a classic script (not an ES module)
var g = 1;
let h = 2;
console.log(globalThis.g); // 1: top-level var becomes a property of the global object
console.log(globalThis.h); // undefined: top-level let/const do notThe comment "run as a classic script" matters. If you save this as a file and run node file.js, you will see undefined for both lines. Node treats a .js file as a CommonJS module by default, and module code is not top-level global code. We will come back to this.
To get real classic-script behavior in Node, you can use the built-in vm module. vm.runInThisContext runs a string of code as a script in the current global scope, the same way a browser runs a <script> tag. Save the following as globals-demo.js and run node globals-demo.js:
const vm = require('node:vm');
vm.runInThisContext(`
var g = 1;
let h = 2;
const k = 3;
function f() { return 'f'; }
`);
console.log(globalThis.g); // 1
console.log(typeof globalThis.f); // 'function'
console.log(globalThis.h, globalThis.k); // undefined undefined
console.log('h' in globalThis); // false
// h and k still exist in the global scope; they are just not properties.
console.log(vm.runInThisContext('h + k')); // 5
console.log(Object.getOwnPropertyDescriptor(globalThis, 'g'));
// { value: 1, writable: true, enumerable: true, configurable: false }
console.log(delete globalThis.g); // false: the property cannot be removed
console.log(globalThis.g); // 1Look at the property descriptor. A top-level var creates a property with configurable: false. You cannot delete it. In sloppy mode delete returns false; in strict mode the same delete throws a TypeError. A property created by plain assignment, such as globalThis.x = 1, is configurable and can be deleted. That difference is one way to tell a declared global from an assigned one.
Classic scripts share one global scope
In a browser, every classic <script> tag on a page runs in the same global scope. A let declared in the first script can be read by the second. That sharing also means names can collide across files, and the rules differ by keyword.
const vm = require('node:vm');
vm.runInThisContext('var shared = 1;');
vm.runInThisContext('var shared = 2;'); // fine: var can be redeclared
console.log(globalThis.shared); // 2
vm.runInThisContext('let only = 1;');
try {
vm.runInThisContext('let only = 2;'); // second script, same name
} catch (e) {
console.log(e.name); // 'SyntaxError'
}
try {
vm.runInThisContext('var only = 3;'); // var cannot reuse a global let name either
} catch (e) {
console.log(e.name); // 'SyntaxError'
}
try {
vm.runInThisContext('let shared = 3;'); // let cannot reuse a global var name
} catch (e) {
console.log(e.name); // 'SyntaxError'
}The engine checks for these conflicts before the new script runs any code. That is why the error is a SyntaxError, even though the clash is with a different file. When a script fails this check, none of it runs. Not even its first line executes.
This is a real risk on pages that load third-party scripts. Two libraries that both declare let config at the top level will break each other. A pair that both use var config will silently overwrite each other's value, and that is often worse.
Shadowing an existing global property
A top-level let is allowed to use the same name as an existing configurable property of the global object. Because lookup checks the declarative record first, the let wins for plain-name reads, and the property stays unchanged:
const vm = require('node:vm');
globalThis.color = 'from property'; // configurable property
vm.runInThisContext("let color = 'from let';");
console.log(vm.runInThisContext('color')); // 'from let'
console.log(globalThis.color); // 'from property'Now one name has two values, which depending on how you access it. Avoid this on purpose, but recognize it when debugging.
Non-configurable properties are protected. undefined, NaN, and Infinity are non-configurable properties of the global object, so a top-level let undefined = 1; in a classic script is a SyntaxError. A top-level var undefined = 1; is allowed but has no effect, because the property is also read-only.
The browser gotcha: var name
Because top-level var writes to the global object, it also runs into whatever the host already put there. In a browser, window.name is a built-in property with a setter that converts any value to a string.
// Browser, classic script only (for example, a fresh page's console)
var name = 42;
console.log(name, typeof name); // '42' 'string'The var doesn't create a new variable. It reuses the existing window.name property, and the setter turns 42 into '42'. The value also survives page reloads within the same tab, because the browser stores window.name per tab. Other browser globals with similar surprises include status, top, parent, length, and origin. You can't assign to top at all.
In a fresh page, let name = 42 creates a binding in the declarative record and shadows window.name, so typeof name is 'number'. This shows why let and const are safer at the top level. They don't touch the global object, so they can't trip over its built-in properties.
Modules change the rules
Everything above applies to classic scripts. Most modern code runs as modules instead, and in a module the top level is not the global scope.
ES modules
An ES module (a <script type="module">, an .mjs file, or a .js file in a package with "type": "module") has its own module scope. Top-level declarations of any kind stay inside the module.
// Save as module-demo.mjs and run: node module-demo.mjs
var g = 1;
let h = 2;
function f() {}
console.log(globalThis.g); // undefined
console.log(globalThis.h); // undefined
console.log(globalThis.f); // undefined
console.log(this); // undefined: top-level this in a moduleModules are also always in strict mode, which the next chapter on accidental globals relies on. If a module really needs to publish a global, it has to say so explicitly with globalThis.myLib = ....
CommonJS in Node.js
Node wraps every CommonJS file in a function before running it, roughly like this:
(function (exports, require, module, __filename, __dirname) {
// your file's code goes here
});Your top-level var is therefore a local variable of that wrapper function. It is function-scoped, exactly as the earlier chapter on var described, so it never reaches globalThis:
// Save as cjs-demo.js and run: node cjs-demo.js
var g = 1;
console.log(globalThis.g); // undefined
console.log(this === module.exports); // trueSummary by context
| Where the code runs | Top-level `var` / `function` on `globalThis`? | Top-level `let` / `const` on `globalThis`? | Shared with other files by name? |
|---|---|---|---|
| Browser classic `<script>` | Yes (non-configurable) | No (global declarative record) | Yes, all classic scripts share it |
| `vm.runInThisContext`, browser console | Yes | No | Yes |
| ES module (browser or Node) | No | No | No, use `export` / `import` |
| Node CommonJS file | No | No | No, use `module.exports` / `require` |
| Node REPL | Yes | No | Yes, within the session |
Practical guidance
- Treat
globalThisproperties as a public, shared namespace. Write to them only on purpose, with an explicit assignment such asglobalThis.APP_VERSION = '1.2.0', never as a side effect ofvar. - Prefer modules. They remove almost every issue in this chapter, because nothing leaks to the global scope unless you put it there.
- In classic scripts that must share state, wrap code in a function or a block, or use a single namespace object, to keep the number of top-level names small.
- Don't use
varat the top level of a classic script unless you specifically need a global object property for old code that readswindow.something.
Exercise
In a browser, a page loads two classic scripts. a.js contains let apiUrl = '/v1'; and b.js contains var apiUrl = '/v2'; console.log('b loaded');. What happens when b.js loads, and does 'b loaded' print?
Show answer
b.js fails with a SyntaxError before any of its code runs, because a var cannot be declared with the same name as an existing global lexical (let) binding. 'b loaded' never prints, and apiUrl stays '/v1'.
Exercise
The following code runs as a classic script: var total = 10; let count = 3;. Give the result of each expression: globalThis.total, globalThis.count, 'count' in globalThis, delete globalThis.total (sloppy mode), and total + count.
Show answer
globalThis.total is 10. globalThis.count is undefined. 'count' in globalThis is false. delete globalThis.total returns false, because a top-level var creates a non-configurable property. total + count is 13, because both are still reachable by name in the global scope.
Exercise
A developer runs var g = 1; console.log(globalThis.g); in the Chrome console and sees 1. They paste the same two lines into app.mjs and run node app.mjs, and see undefined. Explain why, and show how to make the value a global property in the module on purpose.
Show answer
The console runs input as a classic script, where a top-level var becomes a property of the global object. An .mjs file is an ES module, so its top-level declarations live in module scope and never touch globalThis. To publish the value on purpose, assign it explicitly: globalThis.g = 1;.
Exercise
In a fresh browser tab, why does var name = [1, 2]; console.log(name.length); print 3 instead of 2?
Show answer
window.name already exists as a built-in property with a setter that converts values to strings. The top-level var reuses that property instead of creating a new variable, so the array becomes the string '1,2', whose length is 3. Using let name in a fresh page would create a separate binding and keep the array.