globalThis - Access environment-agnostic global `this` value

shahzaibkhalid

Shahzaib Khalid

Posted on August 27, 2019

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. ✌️

πŸ’– πŸ’ͺ πŸ™… 🚩
shahzaibkhalid
Shahzaib Khalid

Posted on August 27, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related