GlobalThis Is The One Global Object
globalThis exists in browsers, workers and Node while window and global do not, so library code reads and registers runtime flags through one universal handle.
Code
// One codebase may run in a browser, a worker, or Node: never assume window or global exists
console.log('typeof window ->', typeof window); // browser 'object', Node 'undefined'
console.log('typeof global ->', typeof global); // Node 'object', browser 'undefined'
console.log('typeof globalThis ->', typeof globalThis); // 'object' everywhere
// globalThis is the only global handle present in every runtime
console.log('same Math:', globalThis.Math === Math);
console.log('same JSON:', globalThis.JSON === JSON);
// Builtins read through it too: Math, JSON, console all hang off the same object
console.log('Math.max via globalThis:', globalThis.Math.max(3, 9));
// Register runtime flags once; any module can read them without import cycles
globalThis.RUNTIME_FLAGS ??= { verbose: false, retries: 3 };
globalThis.RUNTIME_FLAGS.verbose = true;
console.log('flags:', globalThis.RUNTIME_FLAGS.verbose, globalThis.RUNTIME_FLAGS.retries);Output
Captured from a sandboxed run of this snippet in the build pipeline.
typeof window -> undefined
typeof global -> object
typeof globalThis -> object
same Math: true
same JSON: true
Math.max via globalThis: 9
flags: true 3What the demo unifies
The three typeof probes print the runtime split: window is object in browsers and undefined in Node, global is the reverse, while globalThis is object everywhere, the one handle every host provides.
Builtins hang off that same object: globalThis.Math === Math and globalThis.JSON === JSON both print true, and Math.max through globalThis works identically. The final block stores RUNTIME_FLAGS on globalThis with ??= and mutates it, so any module can read the flags without import cycles.
Points to remember
- Never assume window or global exists; probe or use globalThis.
- ??= seeds the flag object only on the first run.
Interactive Tools for This Topic
FAQ
- Why prefer globalThis over window?
- window exists only in browsers; globalThis resolves in browsers, workers and Node alike, so one registration point works across all of them.
Report a problem with this exampleOpens a pre-filled issue on GitHub.