Let's get straight to the point.
global and globalThis both refer to JavaScript's global object, but they differ in scope and compatibility across environments.
What is global??
global is NodeJS-specific and serves as the top-level object containing built-in functions like console and setTimeout.
It does not exist in browsers, where attempting to access it throws a ReferenceError.
This environment-specific nature limits its use to server-side code.
global is only specific to NodeJS as will give different result based on different enviroment.
- Browsers: window
- Node.js: global
- Web Workers: self
- Strict mode functions: undefined
This made writing universal JavaScript code painful. Before ES2020, you needed this ugly code to get the global object:
function getGlobalObjectOldWay() {
// Browser
if (typeof window !== 'undefined')
return window;
// NodeJS
if (typeof global !== 'undefined')
return global;
// Web Worker
if (typeof self !== 'undefined')
return self;
// Fallback
return this;
}
console.log('Old way (Node.js):', getGlobalObjectOldWay());
What is globalThis??
So we already saw the problem with global and to solve this globalThis was introduced in ES2020. globalThis is a standardized, cross-platform way to access the global object that works everywhere - browsers (window), Node.js (global), and Web Workers (self).
globalThis solves this by providing one consistent reference across all environments. In global scope, this equals globalThis, making it memorable.
| Aspect | global | globalThis |
|---|---|---|
| Environments | Node.js only linkedin | All (browsers, Node, Workers) coreui |
| Standardization | Non-standard linkedin | ES2020 standard developer.mozilla |
| Availability | ReferenceError in browsers linkedin | Always works newline |
| Polyfill Need | None (Node-only) | Rare, for old browsers blog.logrocket |
Use globalThis for shared codebases, like your full-stack projects, to avoid environment-specific bugs. However, use global when you're explicitly writing Node.js-specific code.
Top comments (0)