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

EnvironmentLegacy GlobalModern (βœ…)
BrowserwindowglobalThis
Node.jsglobalglobalThis
Web WorkerselfglobalThis

🧠 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!" πŸ§™β€β™‚οΈ