globalThis - Access environment-agnostic global `this` value
Shahzaib Khalid
Posted on August 27, 2019
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');
}
}
Using globalThis
- it drills-down to a single line and environment-agnostic β
π₯
const doesSetExists = () => typeof globalThis.Set === 'function';
Hope you learned something new today. Do let me know what do you think about this Dev Tip in the comments below. π
Peace. βοΈ
Posted on August 27, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.