DEV Community

Shahzaib Khalid
Shahzaib Khalid

Posted on

globalThis - Access environment-agnostic global `this` value

Hey! 👋

Check out today's Dev Tip! 👇

Follow me on Twitter @shahzaibkhalid for more Dev Tips! ✨

globalThis provides a standard way of accessing the global this value i.e. the global object in an environment-agnostic way. 🚀

🛑 This is a stage-3 proposal on the ECMAScript list of proposals and although the functionality is shipped in most of the new browsers, consider polyfilling it to support older browsers.

Accessing the global object requires different syntax in different JavaScript environments:

👉 window or frames - On the web
👉 self - In Web Workers
👉 global - In Node.js

Let's suppose we want to share some functionality on both, Web and Node.js, e.g. checking if Set natively exists in our environment
or not? We've to check the environment first! ❌

const doesSetExists = () => {
  if (typeof window !== 'undefined') {
    return typeof window.Set === 'function';
  } else if (typeof global !== 'undefined') {
    return typeof global.Set === 'function';
  } else {
    throw new Error('Unable to locate global object');
  }
}
Enter fullscreen mode Exit fullscreen mode

Using globalThis - it drills-down to a single line and environment-agnostic ✅ 🔥

const doesSetExists = () => typeof globalThis.Set === 'function';
Enter fullscreen mode Exit fullscreen mode

Hope you learned something new today. Do let me know what do you think about this Dev Tip in the comments below. 👀

Peace. ✌️

Top comments (0)