Understanding globalThis in JavaScript
π What is globalThis?
globalThis is a standard way to access the global object across all JavaScript environments π β whether you're in a browser, Node.js, or even a Web Worker.
Note
Before globalThis, developers had to use environment-specific globals like window, global, or self.
π‘ Why globalThis?
JavaScript has different global objects in different environments:
- window β in browsers π§
- global β in Node.js βοΈ
- self β in Web Workers π οΈ
This made writing cross-platform code difficult. The introduction of globalThis solves this problem by providing a universal global object identifier. π
π§ͺ How to Use It
Using globalThis
// Define a global variable
globalThis.appName = "MyApp";
console.log(globalThis.appName); // MyAppπ Works Everywhere
Cross-environment Example
function getEnv() {
if (globalThis.window) return "Browser";
if (globalThis.global) return "Node.js";
if (globalThis.self) return "Web Worker";
}
console.log(getEnv());π« Avoiding Legacy Globals
Avoid using window or global if you want your code to run everywhere. Prefer globalThis for modern, platform-independent scripts. π§Ό
Note
globalThis was introduced in ECMAScript 2020 and is now widely supported. Use polyfills if targeting older environments.
π Comparing Global Objects
| Environment | Legacy Global | Modern (β ) |
|---|---|---|
| Browser | window | globalThis |
| Node.js | global | globalThis |
| Web Worker | self | globalThis |
π§ Summary
- globalThis is the global object across all JavaScript environments.
- Introduced in ES2020 to solve environment inconsistency.
- Preferred over legacy globals like window, global, and self.
π References
>>"One global to rule them all β globalThis!" π§ββοΈ