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 ==>
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