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! ❌

javascript 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 βœ… πŸ”₯

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