GlobalThis for Universal Code
You'll learn how to write JavaScript that accesses global objects reliably across any environment.
The Cross-Environment Challenge
Before globalThis, writing code that worked everywhere was awkward. In browsers, the global object is window. In Node.js, it's global. In Web Workers, it's self. You'd often see ugly code checking which environment you're in:
const globalObject = typeof window !== 'undefined' ? window :
typeof global !== 'undefined' ? global :
typeof self !== 'undefined' ? self : {};
Enter globalThis
globalThis is a standardized reference to the global object that works everywhere—browsers, Node.js, workers, any JavaScript environment. It's like a universal adapter:
// Works in browsers, Node.js, workers, etc.
globalThis.mySharedValue = 42;
console.log(globalThis.mySharedValue); // 42
Why It Matters
Think of globalThis as a guaranteed meeting place. No matter which JavaScript "building" you're in (browser, server, worker), globalThis points to the lobby everyone shares.
This is essential for:
- Library authors who want one codebase for all platforms
- Testing code across different environments
- Accessing built-in globals without environment checks
// Reliably access setTimeout anywhere
globalThis.setTimeout(() => {
console.log('Universal!');
}, 1000);
Practical Example
// Setting a global fallback value
if (!globalThis.fetch) {
globalThis.fetch = myCustomFetch;
}
Key Takeaway: globalThis is your universal reference to the global object, eliminating environment-specific checks and making your code truly portable.