Understanding globalThis in Node.js and JavaScript

Stop Getting Confused Between this, global, window, and self ==> Meet globalThis!

In JavaScript, accessing the global object was always tricky ==> especially when switching between environments like browsers, Node.js, or Web Workers.

Here’s how it used to work ==>

  • In Browser => global object = window
  • In Web Worker => global object = self
  • In Node.js => global object = global
  • And sometimes this would point to the global scope… sometimes not 😅

This inconsistency made code hard to reuse across environments.

Then came globalThis Introduced in ES2020, globalThis provides one universal reference to the global object — no matter where your JavaScript runs.

// Old way ❌
const root =
  typeof window !== "undefined" ? window :
  typeof global !== "undefined" ? global :
  this;

// Modern way ✅
const root = globalThis;

console.log(root === globalThis); // true everywhere 🌎        

Why it’s useful:

✅ Works in any JS environment (Browser, Node.js, Deno, Workers)

✅ Cleaner and more readable code

✅ No more typeof window checks

✅ Great for reusable libraries and frameworks

Thanks to

Learning this clearly wouldn’t be possible without NamasteDev.com and the amazing explanations by Akshay Saini👏 Truly helps in building strong JS fundamentals!

#JavaScript #TypeScript #Frontend #Backend #WebDevelopment #MERN #ReactJS #NodeJS #Programming #CleanCode #Developers #LearningInPublic #NamasteJavaScript #TechCommunity #JSFundamentals

To view or add a comment, sign in

More articles by Kaumil Patel

Explore content categories