globalThis is a built-in object in JavaScript that provides a standard way to access the global object, regardless of the environment (browser, Node.js, etc.). It was introduced in ECMAScript 2020 (ES11) to unify how developers access the global object in different contexts.
Why globalThis?
Before globalThis, accessing the global object required environment-specific approaches:
This inconsistency made it harder to write universal JavaScript code. With globalThis, you can reliably access the global object without worrying about the environment.
// Browser environment console.log(globalThis === window); // true // Node.js environment console.log(globalThis === global); // true // Accessing global variables globalThis.myGlobalVar = 42; console.log(myGlobalVar); // 42
Use Cases
- Universal Access to the Global Object.
You can write code that works in both browser and Node.js environments without checking for the global object explicitly:
const globalObj = globalThis; // Works everywhere
- Declaring Global Variables Dynamically.
Useful in scenarios like polyfills or feature detection:
if (! globalThis.myFeature) { globalThis.myFeature = "This is a polyfill"; }
- Library Development.
Libraries often use globalThis to attach global variables or configurations in a cross-environment manner.
globalThis is a modern and cleaner way to handle the global object across different JavaScript environments, making your codebase more consistent and portable.