The JavaScript globalThis object
The globalThis keyword is a standard, universal reference to the global object that works everywhere — it's window in browsers, global in Node, and self in web workers. Use globalThis instead of those environment-specific names when you need to access or define a global in portable code.
Overview
globalThis solves an old portability headache: the global object had a different name in every environment. In a browser it was window (or self in workers); in Node it was global. Code that needed the global object had to sniff the environment or use brittle tricks. globalThis is the single, standard name that points to the global object everywhere.
You reach for it when you genuinely need the global scope in code that must run across environments — a library checking for a global feature, a polyfill installing itself, or detecting whether you're in a browser (typeof globalThis.document !== "undefined"). In ordinary app code that targets one environment, you can still just use window; globalThis matters most for portable libraries and shared modules.
A word of caution that applies to all global access: relying on globals is usually a smell. Modules, imports and explicit parameters are cleaner than reaching into global scope. Use globalThis when you truly need the global object, not as a convenient dumping ground for shared state.
Syntax
globalThis // the global object, everywhere
globalThis.window // browser
globalThis.global // Node (older code)
globalThis.self // web workers
// feature detection
if (typeof globalThis.fetch === "function") { /* ... */ }
Example
<pre id="out" style="font:14px ui-monospace,monospace"></pre>
<script>
const inBrowser = typeof globalThis.document !== 'undefined';
const hasFetch = typeof globalThis.fetch === 'function';
document.getElementById('out').textContent =
'globalThis === window? ' + (globalThis === window) + '\n' +
'in a browser? ' + inBrowser + '\n' +
'has fetch? ' + hasFetch;
</script>
Best practices
- Use
globalThisfor portable code that must run in browsers, Node and workers. - Prefer it over environment-specific names (
window,global,self) in shared libraries. - Use it for feature detection:
typeof globalThis.someAPI. - Avoid globals in general — modules and explicit parameters are cleaner than global state.
Frequently asked questions
What is globalThis in JavaScript?
window in browsers, global in Node, self in workers.When should I use globalThis?
window is fine.Is globalThis the same as window?
globalThis is window. In Node it's global, and in a worker it's self. That portability is the point.