Difference between global & globalThis

Published: (March 9, 2026 at 12:52 PM EDT)
2 min read
Source: Dev.to

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 as console and setTimeout. It does not exist in browsers; accessing it there throws a ReferenceError.
  • 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)

EnvironmentGlobal identifier
Browserswindow
Node.jsglobal
Web Workersself
Strict‑mode functionsundefined

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

FeatureglobalglobalThis
EnvironmentsNode.js onlyBrowsers, Node.js, Web Workers
StandardizationNon‑standard (Node.js specific)ES2020 standard (see MDN)
AvailabilityThrows ReferenceError in browsersAlways defined
Polyfill neededNone (Node‑only)Rare, only for very old browsers

References:

When to use which

  • Use globalThis for shared codebases (e.g., full‑stack projects) to avoid environment‑specific bugs.
  • Use global only when you are explicitly writing Node.js‑only code.
0 views
Back to Blog

Related posts

Read more »