Difference between global & globalThis
Source: Dev.to
Overview
global and globalThis both refer to JavaScript’s global object, but they differ in scope and compatibility across environments.
global– Node.js‑specific. It is the top‑level object that contains built‑in functions such asconsoleandsetTimeout. It does not exist in browsers; accessing it there throws aReferenceError.globalThis– Introduced in ES2020 as a standardized, cross‑platform way to access the global object. It works in browsers (window), Node.js (global), and Web Workers (self).
Environment‑specific globals (pre‑ES2020)
| Environment | Global identifier |
|---|---|
| Browsers | window |
| Node.js | global |
| Web Workers | self |
| Strict‑mode functions | undefined |
Before globalThis, writing universal JavaScript required a series of checks:
// Get the global object in a way that works across environments
function getGlobalObjectOldWay() {
// Browser
if (typeof window !== 'undefined') {
return window;
}
// Node.js
if (typeof global !== 'undefined') {
return global;
}
// Web Worker
if (typeof self !== 'undefined') {
return self;
}
// Fallback (e.g., non‑strict function context)
return this;
}
console.log('Old way (Node.js):', getGlobalObjectOldWay());
globalThis – the modern solution
globalThis provides a single, consistent reference to the global object across all JavaScript environments. In the global scope, this is equal to globalThis, making it easy to remember.
Comparison
| Feature | global | globalThis |
|---|---|---|
| Environments | Node.js only | Browsers, Node.js, Web Workers |
| Standardization | Non‑standard (Node.js specific) | ES2020 standard (see MDN) |
| Availability | Throws ReferenceError in browsers | Always defined |
| Polyfill needed | None (Node‑only) | Rare, only for very old browsers |
References:
- MDN Web Docs – globalThis
When to use which
- Use
globalThisfor shared codebases (e.g., full‑stack projects) to avoid environment‑specific bugs. - Use
globalonly when you are explicitly writing Node.js‑only code.