Difference between global & globalThis

Leader posted Originally published at dev.to 1 min read

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.

More Posts

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelskiverified - Apr 9

Sovereign Intelligence: The Complete 25,000 Word Blueprint (Download)

Pocket Portfolioverified - Apr 1

5 Web Dev Pitfalls That Are Silently Killing Your Projects (With Real Fixes)

Dharanidharan - Mar 3
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!