Sub topic 9
Global Objects and Environment Detection
Each JavaScript runtime gives your code a global object, which is where built-in values and host APIs are stored. The browser and Node.js name this object differently, fill it with different things, and treat top-level variables differently. This chapter covers what lives on each global, how globalThis connects them, and how to work out safely which environment your code is running in.
This chapter assumes you have read the earlier chapters on loading scripts in the browser, running scripts with Node.js, and ES modules versus CommonJS. You should also be comfortable with typeof and optional chaining (?.).
The working model: one global object, many names
A global object is the object at the end of every scope chain. If the engine looks up an identifier such as setTimeout and does not find it in any enclosing scope, it checks the global object. The ECMAScript specification defines only a small part of what the global object holds: Array, Promise, JSON, Math, globalThis, and the other language built-ins. The host adds everything else.
| Environment | Global object's own names | Host-specific globals | `globalThis` points to |
|---|---|---|---|
| Browser main thread | `window`, `self`, `frames` | `document`, `location`, `localStorage`, `alert` | the `Window` object |
| Web Worker | `self` | `postMessage`, `importScripts` (classic workers) | the `WorkerGlobalScope` object |
| Node.js | `global` | `process`, `Buffer`, `require` (CommonJS only), `__dirname` (CommonJS only) | the Node.js global object |
| Shared by all modern runtimes | `globalThis` | `fetch`, `URL`, `console`, `setTimeout`, `structuredClone`, `queueMicrotask` | n/a |
globalThis was added in ES2020 to fix a long-standing annoyance. Before it existed, code that needed the global object had to try window, then self, then global, and each of these throws a ReferenceError in at least one environment. globalThis exists everywhere and always refers to that runtime's global object.
`process` is a property of the global object
People new to Node.js often treat process as a global object in its own right. It is just one property of the global object, like document in the browser. It describes the current Node.js process: process.argv, process.env, process.versions, process.platform, process.exit(), and similar. Browsers have no process, so any bare reference to it in browser code throws:
// In a browser console:
process.env.NODE_ENV; // ReferenceError: process is not definedTop-level scope is not always global scope
The second half of the model is about which top-level declarations end up on the global object. The answer depends on how the file was loaded, and getting it wrong causes many "works here, undefined there" bugs.
| How the file is loaded | Top-level `var` / function declaration | Top-level `let` / `const` / `class` | Top-level `this` |
|---|---|---|---|
| Classic browser script | becomes a property of `window` | global, but not a property of `window` | `window` |
| Browser ES module | module-scoped | module-scoped | `undefined` |
| Node.js CommonJS (`.cjs`) | module-scoped | module-scoped | `module.exports` |
| Node.js ES module (`.mjs`) | module-scoped | module-scoped | `undefined` |
Only classic browser scripts leak declarations onto the global object. In CommonJS, Node.js wraps each file in a function, so top-level variables are local to that function. require, module, exports, __filename, and __dirname are parameters of that wrapper. They are not real globals, which is why they do not exist in ES modules.
Save this as scope.cjs and run it with node scope.cjs:
// scope.cjs
var counter = 1;
function helper() {}
console.log(globalThis.counter); // undefined: var stayed in module scope
console.log(typeof globalThis.helper); // 'undefined'
console.log(this === module.exports); // true
globalThis.shared = 'visible to every module';
console.log(shared); // 'visible to every module'Compare a classic script in a page:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Scope</title></head>
<body>
<script>
var counter = 1;
let hidden = 2;
console.log(window.counter); // 1
console.log(window.hidden); // undefined, though `hidden` is still readable from other classic scripts
</script>
</body>
</html>Detecting the environment safely
Sometimes code needs to know where it is running. The main rule is never to reference a possibly missing global by its bare name. typeof is the only operator that does not throw for an undeclared identifier:
// Safe: typeof returns 'undefined' for undeclared names
console.log(typeof window); // 'undefined' in Node.js
// Unsafe: throws ReferenceError in Node.js
// if (window) { ... }
// Also safe: property access on globalThis returns undefined
console.log(globalThis.window === undefined); // true in Node.jsHere is a detection module that tells the common cases apart. Save it as env.mjs:
// env.mjs
export function detectEnvironment() {
if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
return 'browser-main';
}
if (
typeof WorkerGlobalScope !== 'undefined' &&
typeof self !== 'undefined' &&
self instanceof WorkerGlobalScope
) {
return 'web-worker';
}
if (typeof process !== 'undefined' && process.versions?.node != null) {
return 'node';
}
return 'unknown';
}
console.log(detectEnvironment());Running node env.mjs prints node. If you load the same file in a page with <script type="module" src="env.mjs">, the console shows browser-main.
The order of the checks matters. The browser check comes first and requires both window and window.document, so a stray window variable on its own does not count as a match. The worker check uses instanceof WorkerGlobalScope because workers have self but no window. The Node.js check reads process.versions.node instead of just process, because bundlers and test setups sometimes define a fake process object.
Common errors and gotchas
Detection signals that lie
Environment checks are heuristics, and each signal has known false positives:
- jsdom, used by test runners such as Jest and Vitest, defines
windowandwindow.documentinside Node.js. Your "browser" branch will run during tests. That is usually what the test author wants, but it surprises people. - Node.js 21 and later define a global
navigator, withnavigator.userAgentset to a string likeNode.js/22. Treatingtypeof navigator !== 'undefined'as proof of a browser is now wrong. - Bun and Deno both set
process.versions.nodefor compatibility, so the Node.js check matches them too. If the difference matters, checktypeof Bunortypeof Denofirst. - Bundlers used to inject a
processshim into browser builds, and some configurations still do. Code that branches ontypeof processcan take the Node.js path in a browser.
Prefer feature detection
Most of the time you don't need to know the runtime. You need to know whether a particular API exists. Test for the API you are about to use:
// clone.mjs
export function deepClone(value) {
if (typeof globalThis.structuredClone === 'function') {
return globalThis.structuredClone(value);
}
return JSON.parse(JSON.stringify(value)); // fallback with known limits
}
console.log(deepClone({ a: [1, 2, { b: 3 }] }));Feature detection keeps working when a runtime adds an API, as Node.js did with fetch in version 18 and navigator in version 21. Runtime-name checks have to be updated every time that happens. The next chapter builds on this idea to write modules that run unchanged in both environments.
Polluting the global object
Writing to globalThis makes a value visible to every module in the realm, which is the set of code sharing one global object. That includes third-party code. Name collisions are silent. If you really need a global, for example a polyfill, define it only when it is missing:
if (typeof globalThis.queueMicrotask !== 'function') {
globalThis.queueMicrotask = (fn) => Promise.resolve().then(fn);
}`global` and `window` in shared code
Code meant for more than one environment should never use global or window just to reach the global object. global throws in browsers, and window throws in Node.js and in workers. Use globalThis. Use window only when you actually mean the browser's Window object and its page-specific features.
Exercise
A file contains var mode = 'dev'; console.log(globalThis.mode);. What does it print when loaded (a) as a classic browser script, (b) as a browser module script, (c) as app.cjs under Node.js, and (d) as app.mjs under Node.js?
Show answer
(a) 'dev', because top-level var in a classic script becomes a property of window, which is globalThis. (b) undefined, because module top-level declarations are module-scoped. (c) undefined, because Node.js wraps CommonJS files in a function, so var is local to that wrapper. (d) undefined, for the same reason as (b).
Exercise
A library checks if (typeof navigator !== 'undefined') { useBrowserPath(); }. Users report that it takes the browser path on Node.js 22. Explain why, and rewrite the check using feature detection for the case where useBrowserPath needs the DOM.
Show answer
Node.js 21 and later define a global navigator, so the check passes in Node.js. Test for the feature the code actually needs instead: if (typeof document !== 'undefined' && typeof document.createElement === 'function') { useBrowserPath(); }. This passes only where a DOM exists, such as a browser main thread or jsdom.
Exercise
Why does if (process) { ... } crash in a browser while if (typeof process !== 'undefined') { ... } does not? Give a third safe form.
Show answer
Reading an undeclared identifier throws a ReferenceError, and process is undeclared in browsers. typeof is specified to return 'undefined' for undeclared identifiers without throwing. A third safe form is if (globalThis.process !== undefined), because reading a missing property of an object returns undefined instead of throwing.